How to select a specific column in LINQ?

I need to select a specific column from my DataTable using linq I use this code

ds.Table[0].AsEnumerable().Where<DataRow>(r=>r.Field<int>("productID")==23).CopyToDataTable();

~

But it gives me all the columns and I only need PRODUCTNAME, DESCRIPTION, PRICE

How can I write this query?

+5
source share
2 answers

To deploy a bit to @lazyberezovsky, you can use an anonymous type projection to get all the fields you need:

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 enter your product fields, descriptions and prices, so you will have to replace them.

+4
source

Use selection method:

ds.Table[0].AsEnumerable()
           .Where<DataRow>(r=>r.Field<int>("productID")==23)
           .Select(r => r.Field<int>("productID"));

UPDATE: if you need to select multiple columns, you can return an 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")
                        };

, (CopyToDataTable DataRow). . . CopyToDataTable, T DataRow .

+6

All Articles