Linq multi column grouping and averaging

419 views Asked by At

I'm trying to get the average of some numbers after grouping but it just won't group for me. Why isn't this doing what I think it should?

var eventInfo = from eventData in dt.AsEnumerable()
    group eventData by new
        {
            Phase1Minutes = eventData.Field<decimal>("Phase1Minutes"),
            Phase2Minutes = eventData.Field<decimal>("Phase2Minutes"),
            TechnologyType = eventData.Field<string>("TechnologyType"),
            TechnologySubType = eventData.Field<string>("TechnologySubType")
        } into g
    select new
    {
        Phase1Avg = g.Average(x => x.Field<decimal>("Phase1Minutes")),
        Phase2Avg = g.Average(x => x.Field<decimal>("Phase2Minutes")),
        g.Key.TechnologyType,
        g.Key.TechnologySubType
    };
1

There are 1 answers

1
Jon Skeet On BEST ANSWER

It makes no sense to average over what you're already grouping by. Just to give a trivial example, imagine grouping people by age, and then finding the average age within each group... they're all the same age!

My guess is you just need to take out the minutes parts of the grouping:

var eventInfo = from eventData in dt.AsEnumerable()
    group eventData by new
        {
            TechnologyType = eventData.Field<string>("TechnologyType"),
            TechnologySubType = eventData.Field<string>("TechnologySubType")
        } into g
    select new
    {
        Phase1Avg = g.Average(x => x.Field<decimal>("Phase1Minutes")),
        Phase2Avg = g.Average(x => x.Field<decimal>("Phase2Minutes")),
        g.Key.TechnologyType,
        g.Key.TechnologySubType
    };