c# - Sorting a list by parent/child relations ship so I have definitely processed a parent before I try to process the child -


i have system people can sent me list<productcategory>.

i need mapping system , save these database.

the incoming data in format:

public string externalcategoryid { get; set; } public string externalcategoryname { get; set; } public string externalcategoryparentid { get; set; } 

the incoming list in no particular order. if externalcategoryparentid null top level category. parent child relationship can depth - i.e. technology > tvs > samsung > 3d > 40" > etc > etc

when i'm saving need ensure i've saved parent - can't save tvs until have saved technology. externalcategoryid int has no relevance on parent child relationship (a parent can have higher or lower id child).

how can order list can loop through , child, have processed it's parent.

the way can think of externalcategoryparentid == null externalcategoryparentid in "top level" list, next set of children... etc. can't best solution. i'd prefer sort first, have single loop process. have found this post, relies on createddate isn't relevant me.

turns out wasn't difficult after all. wrote function - pass in original list , return sorted list.

it works looping through list checking if there items in list have id == current items parentid. if there one, ignore item , continue. if there aren't any, add current item sortedlist , remove original list , continue. ensures items inserted in sorted list after parent.

private list<heisenbergprodmarketplacecategory> sortbyparentchildrelationship(list<heisenbergprodmarketplacecategory> heisenbergmarketplacecategories) {     list<heisenbergprodmarketplacecategory> sortedlist = new list<heisenbergprodmarketplacecategory>();      //we can check category doesn't have parent in same list - if does, leave , continue     //eventually list empty     while(heisenbergmarketplacecategories.count > 0)     {         (int = heisenbergmarketplacecategories.count-1; >= 0; i--)         {             if (heisenbergmarketplacecategories.singleordefault(p => p.externalcategoryid == heisenbergmarketplacecategories[i].externalcategoryparentid) == null)             {                 sortedlist.add(heisenbergmarketplacecategories[i]);                 heisenbergmarketplacecategories.removeat(i);             }         }     }      return sortedlist; } 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

python 3.5 - Pyqtgraph string in x tick -