frosty
frosty

Reputation: 5370

creating a category list using linq

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; }

    }

Upvotes: 0

Views: 147

Answers (2)

Amy B
Amy B

Reputation: 110221

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);
  }
}

Upvotes: 0

Marcote
Marcote

Reputation: 3105

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

Upvotes: 1

Related Questions