tags:

views:

61

answers:

2

I have the following List which contains the following collection.

How i can transform this with linq so that i get nested items.

 var categories = new List<Category>(); // id, parentId, name
        categories.Add(1, 0, "Sport");
        categories.Add(2, 0, "Pets");
        categories.Add(3, 1, "Foot ball");
        categories.Add(4, 2, "Cat");
        categories.Add(5, 3, "Pele");
        categories.Add(6, 4, "whiskers");
        // ie Pets - > Cat - > Whiskers





   public class Category
    {

        public int Id { get; set; }
        public int ParentId { get; set; }
        public ICollection<Category> Categories { get; set; }

    }
+1  A: 

Something like this:

        var nested = categories.GroupBy(c => c.ParentId)
                               .Select(cat => new Category
                               {
                                   ParentId =  cat.Key,
                                   Categories = cat.Select(x => new Category
                                                                    {
                                                                        Id = x.Id
                                                                    }).ToList()
                               });

I did something similar and works but with two levels, if you need something more generic and with multiple levels I'm not sure if you can do it with LINQ at least.

HTH

Markust
A: 

Here's one way to do it. (edit, corrected for orphans, and returning all roots)

List<Category> results = new List<Category>();
Dictionary quickCategories = categories.ToDictionary(c => c.ID);

foreach(var g in categories.GroupBy(c => c.ParentID))
{
  if quickCategories.ContainsKey(g.Key)
  {
    quickCategories[g.Key].Categories = g.ToList();
  }
  else
  {
    results.AddRange(g);
  }
}
David B
hey thanks, i tried the first, but it seems ParentId is not the dictionary. ALso i tried the second, but how do i return a value from this?
frosty
you must have orphans.
David B