user3024750 user3024750 - 1 month ago 15
C# Question

Assign list after join

I have a join statement in LINQ that combines 1 class and 1 List into a new class.

The class I want:

public class ClassResult
{
public string Name {get;set;}
public List<Class2> Class2s {get;set;}
}


Class
1:

public class Class1
{
public string Name {get;set;}
public int ID {get;set;}
public string Description {get;set;}
}


Class2:

public class Class2
{
public string Name {get;set;}
public int ID {get;set;}
}


JOIN:

// Class1List is a List<Class1>
// Class2List is a List<Class2>

from class2 in class2List
join Class1 in Class1List on class2.ID equals Class1.ID

select new ClassResult
{
Name = Class1.Name,
ClassResult = ? ? ?
};


How can I get the
List<Class2>
of all the
Class2
elements that have the same
ID
as
Class1
? And how do I assign it?

Thanks!

Answer

Though it is a bit difficult to understand with the current input I think what you are asking for is GroupJoin:

from c1 in Class1List
join c2 in Class2List on c1.ID equals c2.ID into g
select new ClassResult
{
    Name = c1.Name,
    Class2 = g.ToList()
}
Comments