Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

I would suggest adding a Group property to Person, which you can set via a simple loop on each of your lists. Then you can do this:

IEnumerable<IGrouping<string, Person>> personsGroups = specificPersons.Concat(allPersons).GroupBy(p => p.Group);

Note that this would not make sense if Person is a domain entity and/or exists in your database. Since these groups are for display purposes, use a view model (e.g. PersonViewModel) and add the Group property to that model to avoid changing your domain model.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top