Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain parent instance if using SelectMany on nested collection

Tags:

c#

linq

I have a collection of my model Person:

class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Company {get; set;}
    public IEnumerable<string> Tags {get; set;}
}

and would transform this one by LINQ into another collection grouped by tags. How can I do that?

My approach so far:

var result = PersonCollection
    .SelectMany(m => m.Tags)
    .GroupBy(b => b);

But this throws all informations about the person away.

like image 389
senz Avatar asked Dec 06 '22 12:12

senz


1 Answers

You can persist the Person in an anonymous type:

var result = PersonCollection
    .SelectMany(p => p.Tags.Select(t => new{ Person = p, Tag = t }))
    .GroupBy(x => x.Tag);

Now these groups still contain the tags as key and the persons:

foreach (var tagPersons in result)
{
    Console.WriteLine($"Tag: {tagPersons.Key}");
    Console.Write($" all persons: {string.Join(",", tagPersons.Select(x => x.Person.LastName))}");
}
like image 82
Tim Schmelter Avatar answered Dec 08 '22 12:12

Tim Schmelter