0

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.

T.S.
  • 18,195
  • 11
  • 58
  • 78
Alessandro
  • 107
  • 1
  • 8
  • 1
    Does this answer your question? [Select All columns for all tables in join + linq join](https://stackoverflow.com/questions/1671765/select-all-columns-for-all-tables-in-join-linq-join) – YK1 Nov 17 '22 at 20:40
  • Do you have left join or something, to group it? – T.S. Nov 17 '22 at 20:44

2 Answers2

2

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"

T.S.
  • 18,195
  • 11
  • 58
  • 78
1

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

Diego
  • 127
  • 4