LINQ to SQL - How to select specific columns and return strongly typed list

前端 未结 3 1195
不思量自难忘°
不思量自难忘° 2020-12-08 02:10

I\'m trying to use LINQ to SQL to select a few specific columns from a table and return the result as a strongly typed list of objects.

For Example:



        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 02:42

    Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):

    var result = (from a in new DataContext().Persons
                  where a.Age > 18
                  select new Person { Name = a.Name, Age = a.Age }).ToList();
    

    Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:

    class PersonInformation {
       public string Name {get;set;}
       public int Age {get;set;}
    }
    
    var result = (from a in new DataContext().Persons
                  where a.Age > 18
                  select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
    

    You can freely swap var with List here without affecting anything (as this is what the compiler does).

    Otherwise, if you are working locally with the query, I suggest considering an anonymous type:

    var result = (from a in new DataContext().Persons
                  where a.Age > 18
                  select new { a.Name, a.Age }).ToList();
    

    Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.

    UPDATE:

    If you really want to return a List (which might or might not be the best thing to do), you can do this:

    var result = from a in new DataContext().Persons
                 where a.Age > 18
                 select new { a.Name, a.Age };
    
    List list = result.AsEnumerable()
                              .Select(o => new Person {
                                               Name = o.Name, 
                                               Age = o.Age
                              }).ToList();
    

    You can merge the above statements too, but I separated them for clarity.

提交回复
热议问题