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.
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))}");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With