Read all rows of a specific column using LINQ

It sounds trivial, but I can’t find an elegant answer to this question: how can I read all the rows of a certain column in the row list, for example, using LINQ in the context of the Entity Framework?

+5
source share
2 answers

You can try something simple as shown below:

var rows = dbContext.TableName.Select(x=>x.ColumName); 

where dbContext is the class that you use to β€œchat” with your database, TableName is the name of the table whose column values ​​you want to read, and ColumnName is the name of the column.

Also, if you put a ToList after Select , you will create a list of objects whose type will be the type of the values ​​in the column named ColumnName .

+9
source

Christos answer will just give you IQueryable. If you need an actual list, you need to do something using IQueryable:

 var rows = dbContext.TableName.Select(x=>x.ColumName).ToList(); 

although I could use LINQ syntax:

 var rows = (from c in dbContext.TableName select c.ColumnName).ToList(); 

Two forms are equivalent.

+5
source

All Articles