Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 674
eYe Avatar asked May 07 '15 19:05

eYe


2 Answers

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.

like image 92
Christos Avatar answered Nov 09 '22 05:11

Christos


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.

like image 32
James Curran Avatar answered Nov 09 '22 04:11

James Curran