c# - Find an item in a list -
in c#, if have list of objects each list has list of list items, , each of these list items can list of objects (or single list item), best way retrieve specific list name?
each list , list item has unique name. type attribute in maplocationlistitem either "list" or "listitem".
here classes:
public class maplocationlist { public string name { get; set; } public list<maplocationlistitem> listitems { get; set;} public maplocationlist () { listitems = new list<maplocationlistitem> (); } } public class maplocationlistitem { public string name { get; set;} public string type { get; set;} public string heading { get; set;} public string subheading { get; set;} maplocationlist maplocationlist{ get; set;} } thanks in advance
what have here tree (with 2 types of nodes) (also assuming have no cycles, create graph). traversing tree straightforward problem can solve in general case handful of lines of code:
public static ienumerable<t> traverse<t>( ienumerable<t> source , func<t, ienumerable<t>> childrenselector) { var stack = new stack<t>(source); while (stack.any()) { var next = stack.pop(); yield homecoming next; foreach (var kid in childrenselector(next)) stack.push(child); } } so, have list<maplocationlist> need create function kid items of given node utilize our traverse method. if had 1 type of node we'd kid nodes directly. since have 2 types, need utilize selectmany children of our kid nodes:
var allnodes = rootnodes.traverse(maplocations => maplocations.listitems.selectmany(item => item.list)); from here can first item given name:
var servynode = allnodes.firstordefault(node => node.name == "servy"); c# list object search recursion
No comments:
Post a Comment