0

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
sust86
  • 1,870
  • 2
  • 18
  • 25
  • What criteria do you want the groups of people to be grouped by? – mayabelle Feb 12 '14 at 17:35
  • Each list should result in a group. Maybe this is the point where I do not really understand how this works. There is no other criteria to create the group since each list will be a group. – sust86 Feb 12 '14 at 17:39

2 Answers2

1

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}));
jnovo
  • 5,659
  • 2
  • 38
  • 56
  • This seems like what I was looking for, I'll test this out in a minute. For the second solution with anonymous types - what would the returned type look like? – sust86 Feb 13 '14 at 06:46
  • An `IEnumerable` for an anonymous type containing a `Header` property of type `string` and a `i` property of type `Person` – jnovo Feb 13 '14 at 07:46
0

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.

mayabelle
  • 9,804
  • 9
  • 36
  • 59