Search code examples
c#linqlinq-to-objects

LINQ - Select correct values from nested collection


Consider the following class hierarchy:

public class Foo
{
 public string Name { get; set; }
 public int Value { get; set; }
}
public class Bar
{
 public string Name { get; set; }
 public IEnumerable<Foo> TheFoo { get; set; }
}

public class Host
{
  public void Go()
  {
    IEnumerable<Bar> allBar = //Build up some large list
    //Get Dictionary<Bar, Foo> with max foo value
  }
}

What I would like to do using Linq2Objects is to get an KeyValuePair where for each Bar in the allBBar collection we select the Foo with the maximum Value property. Can this be done easily in a single LINQ statement?


Solution

  • Sure, although my preferred solution uses MaxBy from MoreLINQ:

    var query = allBar.ToDictionary(x => x, // Key
                                    x => x.TheFoo.MaxBy(f => f.Value));
    

    Note that this will go pear-shaped if TheFoo is empty for any Bar instance.