I have to select specific column from my DataTable using linq I am using this code
ds.Table[0].AsEnumerable().Where<DataRow>(r=>r.Field<int>("productID")==23).CopyToDataTable();
~
But it is giving me all columns and I need only PRODUCTNAME , DESCRIPTION , PRICE
How I can write this query?
var Q1 = (ds. Tables[1]. AsEnumerable() .
We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns.
The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.
To expand a bit on @lazyberezovsky, you can use an anonymous type projection to get all of the fields you want:
ds.Table[0].AsEnumerable()
.Where<DataRow>(r => r.Field<int>("productID") == 23)
.Select(r => new { ProductName = r.Field<string>("productName"),
Description = r.Field<string>("description"),
Price = r.Field<decimal>("price") });
I don't know what name and type your product name, description, and price fields are, so you will have to substitute those.
Use Select method:
ds.Table[0].AsEnumerable()
.Where<DataRow>(r=>r.Field<int>("productID")==23)
.Select(r => r.Field<int>("productID"));
UPDATE: In case you need to select several columns, you can return anonymous type:
var query = from row in dt.ds.Table[0].AsEnumerable()
where row.Field<int>("productID")==23
select new {
ProductID = x.Field<string>("productID"),
Foo = x.Field<string>("foo")
};
If you need to copy that data to new table, you'll face problem (CopyToDataTable requires collection of DataRow objects). See How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow to solve this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With