Search code examples
c#linqcollectionviewsource

Using Linq to group objects that contain a list field


I have a class, let's name it as MyClass, with a public field of type IList<AnotherType>:

class MyClass
{
    public IList<AnotherType> MyListProperty {get;}
}

I also have a list of MyClass objects in my app:

list = new List<MyClass>();

I want to get a group from this "list", specifically IOrderedEnumerable<IGrouping<MyClass,AnotherType>> using Linq, which will be used as a source to a CollectionViewSource and will be shown to the user as a grouped ListView. How can I do this?

In other words, I want to merge the "list" into a grouped enumerable with the keys being MyClass instances and values being MyClass.MyListProperty.


Solution

  • If I undestand you correctly, you're looking for something like this:

    list.SelectMany(x => x.MyListProperty.GroupBy(y => x));
    

    This returns IEnumerable<IGrouping<MyClass, AnotherType>>. To make it an IOrderedEnumerable, you need to add .OrderBy(x => x.SomeOrderingProperty); at the end.