简体   繁体   中英

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?

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();

ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM