Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

select

linq

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?

like image 345
PassionateDeveloper Avatar asked Oct 09 '09 08:10

PassionateDeveloper


1 Answers

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.

like image 197
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet