Search code examples
c#linq

LINQ join "select all" returns only the columns of the second table


I need a List of objects whose properties will be the columns' names.

This is my approach:

var list = (from student in context.Student
        join school in context.School
        on student.idSchool equals school.idSchool
        into allcolumns
        from entry in allcolumns
        select entry).ToList();

but list happens to be only a list of Schools. How can I accomplish my goal? Thank you.


Solution

  • The Select Linq expression returns IEnumerable<T> The T can be anonymous type. In your case, if you want only certain columns, you need to express which ones.

    var mylist = 
        from student in context.Student
        join school in context.School on student.idSchool equals school.idSchool
        select new 
        {
            student.idSchool, // if you want specific name - define >> SchoolId = student.idSchool
            student.Property1,
            student.Property2,
            student.Property3,
            school.Property1,
            school.Property2,
            school.Property3,  
        };
    
    

    Now that you have Enumerable of your anonymous type, you can always call ToList/ToArray as needed. Keep in mind, make sure to call it only once and reuse variable because of concept of "deferred execution"