Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from list Lambda or linq

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,

like image 784
hippie Avatar asked Nov 09 '11 13:11

hippie


2 Answers

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.

like image 153
Vladislav Zorov Avatar answered Oct 15 '22 02:10

Vladislav Zorov


You can do it like this:

var result = master.SelectMany(m => m).Where(mo => mo.id == 2);
like image 31
Klaus Byskov Pedersen Avatar answered Oct 15 '22 00:10

Klaus Byskov Pedersen