user1390378
user1390378

Reputation: 433

How to select specific column in LINQ?

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?

Upvotes: 9

Views: 34581

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

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.

Upvotes: 8

AJ.
AJ.

Reputation: 16729

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.

Upvotes: 10

Related Questions