c# - Grouping a list of objects by parent using linq to output child elements -


i have silly problem linq groupby cant work on own.

basically have list of items trying group parentid outing details

var list = new list<groupitem>() {     new groupitem() {id = 1, name = ".net"},     new groupitem() {id = 2, name = "asp.net", parentid = 1},     new groupitem(){id = 3,name = "c#",parentid = 1},     new groupitem(){id = 4,name = "php"},     new groupitem(){id = 5,name = "zend",parentid = 4} };  var group = g in list             group g g.parentid ==null                 grouped             select new             {                 frameworkid = grouped.key,                 items = (from g in list                         g.parentid==g.parentid                         select g).tolist()              };  foreach (var gi in group) {      console.writeline(gi.frameworkid);     foreach (var item in gi.items)     {         console.writeline(item.name);     } } 

what doing wrong?

you query seems complicated:

  1. you should group parentid items have not null
  2. you not need find items again matching parentid because groupby operator you

my preferred solution:

list.where(x => x.parentid != null)     .groupby(x => x.parentid,               (key, elements) =>                  new {                   frameworkid = key,                   items = elements.tolist()                 })     .tolist(); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -