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

Time:11-18

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.

CodePudding user response:

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"

CodePudding user response:

I'm checking your linq, I think you can change like this:

var mylist = from student in context.Student
    join school in context.School
    on student.idSchool equals school.idSchool
    select new 
    {
      Stud = student,
      Scho = school
    };

The variable list will be a Enumerable T, Anonymous type

You could check the result with:

foreach(var item in mylist)
{
    Console.Writeline($"{item.Stud.YourFieldName} | {item.Scho.YourFieldName}");
}

Best Regards

  • Related