Linq Age GroupBy Aggregate Count

时间:2013-07-04 02:40:36

标签: c# linq count aggregate

我无法获得此linq的正确结果。

 var transactions = from trans in tblMemberInfo.AsEnumerable()
                    orderby trans.Field<Int32>("AGE") ascending
                    group trans by trans.Field<Int32>("AGE") into groupTrans

                    select new
                    {                                      
                         ZeroToSix = groupTrans.Count(age => age.Field<Int32>("AGE") >= 0 && age.Field<Int32>("AGE") <= 6) 
                    };

我有一个包含以下数据的数据表。现在,我想把所有的年龄统计在哪里 年龄介于0到5之间。

AGE     Count
0       6
1       6
2       7
3       5
4       5
5       20
6       5
7       5
8       5
9       5
10      5

我希望看到这样的结果。

Age

ZeroToFive = 49
AboveSix = 25

1 个答案:

答案 0 :(得分:2)

检查一下:

// mock data
var data = new List<dynamic> {
    new { Age = 0, Count = 6 },
    new { Age = 1, Count = 6 },
    new { Age = 2, Count = 7 },
    new { Age = 3, Count = 5 },
    new { Age = 4, Count = 5 },
    new { Age = 5, Count = 20 },
    new { Age = 6, Count = 5 },
    new { Age = 7, Count = 5 },
    new { Age = 8, Count = 5 },
    new { Age = 9, Count = 5 },
    new { Age = 10, Count = 5 },
};

var age = new { 
                ZeroToFive = data.Where(x => x.Age < 6).Sum(x => x.Count),
                AboveSix = data.Where(x => x.Age >= 6).Sum(x => x.Count)
              };