tags:

views:

792

answers:

2

I have a collection of collections, all the child collections have the same number of elements. The parent collection does nothing other than hold the child collections.

[0] [Child_0] [ID: 1]
[0] [Child_0] [Amount: 4]
[0] [Child_1] [ID: 2]
[0] [Child_1] [Amount: 7]
[1] [Child_0] [ID: 1]
[1] [Child_0] [Amount: 2]
[1] [Child_1] [ID: 2]
[1] [Child_1] [Amount: 4]
[2] [Child_0] [ID: 1]
[2] [Child_0] [Amount: 5]
[2] [Child_1] [ID: 2]
[2] [Child_1] [Amount: 3]

For my output I don't care about the parent collection. I just want an anonymous type of ID and average of amounts, so for the above it would be

ID     Avg
1      3.66
2      4.66

Language of the response does not matter.

Thanks.

+3  A: 

Hi there, you may be able to us this as a guide

        var items = new[] 
        { 
            new { ID = 1, Amount = 4 }, 
            new { ID = 1, Amount = 5 },
            new { ID = 2, Amount = 5 },
            new { ID = 2, Amount = 3 },
        };

        var results = from item in items group item by item.ID into g select new { ID = g.Key, Avg = g.Average(item => item.Amount) };

        foreach (var result in results)
        {
            Console.WriteLine("{0} - {1}", result.ID, result.Avg);
        }
Rohan West
Much better than my answer. +1
Jeff Yates
+4  A: 

It sounds like a simple selectmany, group and average should do the job; here I'm using anonymous types and arrays purely for convenience of typing...

        // the data
        var outer = new[] {
            new[] {
                new {ID=1,Amount=4}, // [0] [Child_0] [ID: 1, Amount: 4]
                new {ID=2,Amount=7}  // [0] [Child_1] [ID: 2, Amount: 7]
            },
            new[] {
                new {ID=1, Amount=2}, // [1] [Child_0] [ID: 1, Amount: 2]
                new {ID=2, Amount=4}  // [1] [Child_1] [ID: 2, Amount: 4]
            },
            new[] {
                new {ID=1, Amount=5}, // [2] [Child_0] [ID: 1, Amount: 5]
                new {ID=2, Amount=3}  // [2] [Child_1] [ID: 2, Amount: 3]
            }
        };
        var qry = from x in outer
                  from y in x
                  group y by y.ID into grp
                  select new { Id = grp.Key, Avg = grp.Average(z => z.Amount) };

        foreach (var item in qry)
        {
            Console.WriteLine("{0}: {1}", item.Id, item.Avg);
        }
Marc Gravell
winner winner chicken dinner.. thanks..