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&l开发者_如何学JAVAt;Category> Categories { get; set; }
}
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
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);
}
}
精彩评论