Search code examples
listlinqlinq-group

Creating Groups out of two different lists


I guess this is an easy one but I have no clue how to do this.

I have two lists of Persons

List<Person> specificPersons
List<Person> allPersons

I would like to create groups out of the two complete lists like the following with linq.

IEnumerable<IGrouping<string, Person>> personsGroups

The string will be any custom string. I would use this to display both lists separated by a group header in a Windows 8.1 Metro Application ListView using a CollectionViewSource binding to the IEnumerable.


Solution

  • You can do something like this:

    string headerSpecific = "Specific";
    string headerAll = "All";
    
    var query =
        specificPersons.GroupBy(_ => headerSpecific )
        .Union(
        allPersons.GroupBy(_ => headerAll));
    

    Note you have other ways to accomplish similar functionality (although not matching your question's requirements), for instance using anonymous types instead of groups:

    var query =
        specificPersons.Select(p => new { Header = headerSpecific, p})
        .Union(
        allPersons.Select(p => new { Header = headerAll, p}));