Reputation: 714
I have 2 objects as below:
public class object1
{
public int Object1ID { get; set; }
public string SomeValue { get; set; }
public List<object2> ListOfObject2 { get; set; }
}
public class object2
{
public int Object2ID { get; set; }
public string SomeValue2 { get; set; }
public int Object1LinkedID { get; set; }
}
Object1ID and Object2ID are unique ids.
I populate both of them as lists (so I have a list of Object1s and a list of Object2s).
List<Object1> listObject1 = new List<Object1>();
List<Object2> listObject2 = new List<Object2>();
I'd like to add all of the Object2s to Object1 where Object1LinkedID
is equal to Object1
. This can be into a new Object or just an update to original Object1 list.
Upvotes: 0
Views: 1013
Reputation: 2551
var query = from o1 in listObject1
join o2 in listObject2
on o1.Object1ID equals o2.Object1LinkedID
into go2
select new {O1 = o1, O2Coll = go2};
foreach (var rel in query)
{
rel.O1.ListOfObject2.AddRange(rel.O2Coll);
}
or
foreach (var object1 in listObject1)
{
int o1Id = object1.Object1ID;
object1.ListOfObject2.AddRange(listObject2.Where(o => o.Object1LinkedID == o1Id));
}
Upvotes: 0
Reputation: 460138
This should work:
var groups = listObject2.GroupBy(o2 => o2.Object1LinkedID);
foreach(var o1Group in groups)
{
object1 o1 = listObject1.Where(o => o.Object1ID == o1Group.Key).First();
o1.ListOfObject2.AddRange(o1Group);
}
Upvotes: 1