LINQ Grouping through SelectMany - Powerful!

This is the first time I use this feature and I love it very much!

What this feature does is that it flattens your object in relation to your defined selected child object.

So for example, if I have a list of Item object and that object has a List of Category (imagine Item has N:N relationship to Category) and I want to be able to group it based on the Category and display it in such a way so it looks like this:

Category 1
  • Item 1
  • Item 2
  • Item 3
Category 2
  • Item 2
  • Item 4
and so on..

It is easy to get that structure using LINQ!

1
2
3
4
5
6
7
8
9
var orderedResults = items
                    .SelectMany(i => i.Category.Select(r => new { Ctgry = r, Item = i })).ToList()
                    .GroupBy(c => c.Ctgry.CategoryId).ToList()
                    .Select(g => new ItemWithCategory
                    {
                        CategoryName = g.First().Ctgry.Title,
                        Items = g.Select(o => o.Item).ToList()
                    })
                    .OrderBy(o => o.CategoryName).ToList();

That's all you need to do! ^_^ Hope this helps, Andreas

Comments

Popular posts from this blog

SharePoint 2013 anonymous access add attachments to list item

CRM Plugin - Parent and Child Pipeline