PassionateDeveloper
PassionateDeveloper

Reputation: 15158

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

my code is:

            List<Benutzer> users = (from a in dc.Benutzer
                                    select a).ToList();

I need this code but I only want to select 3 of the 20 Columns in the "Benutzer"-Table. What is the syntax for that?

Upvotes: 11

Views: 20440

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1504182

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.

Upvotes: 26

Chris James
Chris James

Reputation: 11731

    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.

Upvotes: 4

TheVillageIdiot
TheVillageIdiot

Reputation: 40512

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.

Upvotes: 1

Related Questions