IEnumerable of averages of one property from IEnumerable<IEnumerable<T>> where T has two properties

.net-3.5, c#

Solution

Using LINQ, you can flatten out the list of lists with `SelectMany`, then `GroupBy` x and `Select` the average:

var averages = customObjectLists
    .SelectMany(l => l)
    .GroupBy(co => co.x)
    .Select(g => new CustomObject { x => g.Key, y = g.Average(co => co.y) });

Problem

I have an `IEnumerable<IEnumerable<CustomObject>>`s where `CustomObject` has an `x` (which is used like a key (in this case `1`, `2`, `3`)) and a `y` value. Some pretend data: ``` { { {1, 2}, {2, 4}, {3, 6}, {4, 8} }, { {1, 2}, {2, 0}, {3, 0}, {4,-2} }, { {1, 2}, {2, 2}, {3, 0}, {4, 0} } } ``` What is the best way I can retrieve the following `IEnumerable<CustomObject>`: `{ {1, 2}, {2, 2}, {3, 2}, {4, 2} }` I.e. the average of the `y` values for each element. Performance needs to be reasonable, so no `.ToList()` or similar can be used. I've been trying various things with LINQ but to no avail. Update @Bort, @Rawling, I've tested your answers and @Rawling's is very slightly faster. @Bort's answer, however, is more readable so I think I will go with that for the moment. Please feel free to keep answers coming!

Original source

Related problems