I have a collection of items coming from a database which has a parentid
value or null.
Here is my class design:
public class Item
{
public
You could use this approach:
Lookup
of parent ids and items with that parent id.Code:
var items = // get from the database... (e.g. as a list)
var lookup = items.ToLookup(x => x.ParentId);
foreach (var item in items)
item.SubItems = lookup[item.Id].ToList();
As @EamonNerbonne commented below, you can get the root elements as well, if you need to:
var roots = lookup[null].ToList();