Linq多列分组和平均

时间:2011-02-07 22:08:30

标签: linq ado.net linq-to-dataset

我试图在分组后获得一些数字的平均值,但它不会为我分组。为什么这不是我认为它应该做的?

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 个答案:

答案 0 :(得分:0)

平均你已经分组的内容是没有意义的。举一个简单的例子,想象一下按年龄对人进行分组,然后找出每个群体中的平均年龄......他们的年龄相同!

我的猜测是你只需要取出分组的分钟部分:

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
    };