Objective
I have following array and would like to group by each child and get its smallest Id
:-
var list = new[]
{
new { Id = 1, Childs = new [] { 'a', 'b' } },
new { Id = 2, Childs = new [] { 'a' } },
new { Id = 3, Childs = new [] { 'a', 'c' } },
new { Id = 4, Childs = new [] { 'b' } },
new { Id = 5, Childs = new [] { 'b' } },
new { Id = 6, Childs = new [] { 'b', 'c' } },
};
Attempt
var groups = list
.SelectMany(item => item.Childs)
.Distinct() // for each unique child
.ToDictionary(
child => child, // with each child as key
child => list.Where(item =>
item.Childs.Any(c =>
c == child)) // get items with corresponding child
.Min(item => item.Id)); // extract min Id
foreach (var g in groups)
{
Console.WriteLine($"{ g.Key }: { g.Value }");
}
// Prints
// a: 1
// b: 1
// c: 3
Rationale
a contains in Id
1, 2 and 3 and the smallest is 1.
Improvement
I'm trying to solve it with LINQ and thinking GroupBy
would be the go-to solution but I'm stuck with splitting each child element as the key.
I would really appreciate if someone have any idea to solve it in a more elegant way! 🙇