Im trying to select from a collection in linq based on an id on an object of that collection.
List<List<myobject>> master = new List<List<myobject>>();
List<myobject> m1 = new List<myobject>();
List<myobject> m2 = new List<myobject>();
master.Add(m1);
master.Add(m2);
m1.Add(new myobject{name="n1",id=1});
m1.Add(new myobject{name="n2",id=2});
m1.Add(new myobject{name="n3",id=3});
m2.Add(new myobject{name="m1",id=1});
m2.Add(new myobject{name="m2",id=2});
m2.Add(new myobject{name="m3",id=3});
What i want is to, with lambda/linq, is to get all the objects with id=2 from the master.
The senario im using this in is a mongodb with this structure.
Thanks,
var result = master.SelectMany(n => n).Where(n => n.id == 2);
SelecMany
will flatten the hierarchical list to one large sequential list, and then Where
will filter for your condition.
You can do it like this:
var result = master.SelectMany(m => m).Where(mo => mo.id == 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With