Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific column in LINQ?

Tags:

c#

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?

like image 967
user1390378 Avatar asked May 15 '12 12:05

user1390378


People also ask

How do I select a single column in LINQ?

var Q1 = (ds. Tables[1]. AsEnumerable() .

How do I select specific columns in Entity Framework?

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.

What is Dynamic Linq?

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.


2 Answers

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.

like image 115
AJ. Avatar answered Sep 30 '22 07:09

AJ.


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.

like image 39
Sergey Berezovskiy Avatar answered Sep 30 '22 08:09

Sergey Berezovskiy