eYe
eYe

Reputation: 1733

Read all rows of a specific column using LINQ

Sounds trivial but I cannot find an elegant answer to this: how do I read all rows of a specific column into a list of strings for instance using LINQ on Entity Framework context?

Upvotes: 5

Views: 7622

Answers (2)

James Curran
James Curran

Reputation: 103515

Christos answer will just give you an IQueryable. If you want an actual List you need to do something with the IQueryable:

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

though I might go for the LINQ syntax:

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

The two forms are equivalent.

Upvotes: 6

Christos
Christos

Reputation: 53958

You could try something as simple as the following:

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

where dbContext is the class you use to "talk" 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.

Furthermore, if you place a ToList after the Select, you will create list of objects whose type would be the type of the values in column called ColumnName.

Upvotes: 11

Related Questions