c# - How can I get all nested items from a collection? -
i have collection of items. 1 item can have item, , item can have item. on.
i not know how many levels of nested items can have item. level of nested items can defined @ run-time.
class person { person person; public person(person _nestedperson) { person = _nestedperson; } public bool isselectedperson { get; set; } public string name { get; set; } } and how items(person) can nested:
ilist<person> list = new list<person>(); (int startindex = 0; startindex < 5; startindex++) { list.add(new person(new person(new person(new person(null) { name="bill", isselectedperson=true})) { name = "jessy", isselectedperson = false }) { name = "bond", isselectedperson =true});//3 nested persons list.add(new person(new person(null) { name = "kendell", isselectedperson = true }) { name="rosy", isselectedperson=true});//2 nested persons //the next time can 1 person without nested item(person). not know how many items(persons) nested //list.add(new person(null) { name="rosy", isselectedperson=true}); } my goal take all objects(without duplicates) of persons(person) isselectedperson=true?
i've played select()
var ee = list.select(x=>x.isselectedfacet==true);//comparison should done here but not want, takes bool values.
update:
my expected result should have 1 object of person unique name. no matter how many there objects same name. take 1 object. sorry misleading. should this:
you can make helper method unwrap nested objects
ienumerable<person> unwrapperson(person p) { list<person> list = new list<person>(); list.add(p); if (p.person != null) list.addrange(unwrapperson(p.person)); return list; } or if person class has 1 nested object (person person;) can use yield construction instead of recursion
static ienumerable<person> unwrapperson(person p) { yield return p; while (p.person != null) { p = p.person; yield return p; } } in order remove duplicate persons, example same name, should implement iequalitycomparer<person> , use distinct method.
class comparer : iequalitycomparer<person> { public bool equals(person x, person y) { return string.equals(x.name, y.name); } public int gethashcode(person obj) { string name = obj.name; int hash = 7; (int = 0; < name.length; i++) { hash = hash * 31 + name[i]; } return hash; } } so final query should similar to:
list.selectmany(p => unwrapperson(p)) .where(x => x.isselectedperson == true) .distinct(new comparer()) 
Comments
Post a Comment