c# - How to get a flattened list from nested class List? -
c# - How to get a flattened list from nested class List<T>? -
i have question using these same examples - question focused on different issue. given next classes:
[xmlroot] public class family { [xmlelement] public list<person> person; } public class person { [xmlattribute("member")] public membertype fellow member { get; set; } [xmlattribute("id")] public int id { get; set; } [xmlelement] public string surname { get; set; } [xmlelement] public string forename { get; set; } [xmlelement("person")] public list<person> people; } public enum membertype { father, mother, son, girl }
if family
has method defined such:
public ienumerable<person> find (func<person, bool> predicate) { // how selectmany flatten list? foreach (var p in family.person.selectmany(p => p)) { if(predicate(p)) { yield homecoming p; } } }
i need able execute predicate on flattened list of person
. in illustration above selectmany
not flattening list had hoped. above won't compile because inferred type cannot determined.
how can family.person collection become 1 flattened list of person?
public ienumerable<person> find(ienumerable<person> input, func<person, bool> predicate) { homecoming input.select(p => { var thislevel = new list<person>(); if(predicate(p)) thislevel.add(p); homecoming thislevel.union(find(p.people ?? new list<person>(), predicate)); } ).selectmany(p => p); }
c# linq-to-objects
Comments
Post a Comment