Simple Linq question: How to select more than one column? Simple Linq question: How to select more than one column? sql sql

Simple Linq question: How to select more than one column?


Here's a query expression:

var users = (from a in dc.Benutzer             select new { a.Name, a.Age, a.Occupation }).ToList();

Or in dot notation:

var users = dc.Benutzer.Select(a => new { a.Name, a.Age, a.Occupation })                       .ToList();

Note that this returns a list of an anonymous type rather than instances of Benutzer. Personally I prefer this approach over creating a list of partially populated instances, as then anyone dealing with the partial instances needs to check whether they came from to find out what will really be there.

EDIT: If you really want to build instances of Benutzer, and LINQ isn't letting you do so in a query (I'm not sure why) you could always do:

List<Benutzer> users = dc.Benutzer    .Select(a => new { a.Name, a.Age, a.Occupation })    .AsEnumerable() // Forces the rest of the query to execute locally    .Select(x => new Benutzer { Name = x.Name, Age = x.Age,                                 Occupation = x.Occupation })    .ToList();

i.e. use the anonymous type just as a DTO. Note that the returned Benutzer objects won't be associated with a context though.


    List<Benutzer> users = (from a in dc.Benutzer                            select new Benutzer{                             myCol= a.myCol,                             myCol2 = a.myCol2                             }).ToList();

I think that's what you want if you want to make the same kind of list. But that assumes that the properties you are setting have public setters.


try:

var list = (from a in dc.Benutzer select new {a.Col1, a.Col2, a.Col3}).ToList();

but now you have list of anonymous object not of Benutzer objects.