LINQ中count计数函数的位置

时间:2014-03-04 01:32:54

标签: linq

我有一个LINQ语句,如下所示:

var pairs = new [] { 
    new { id = 1, name = "ram", dept = "IT", sal = "3000" }, 
    new { id = 2, name = "ramesh", dept = "IT", sal = "5000" }, 
    new { id = 3, name = "rahesh", dept = "NONIT", sal = "2000" },
    new { id = 5, name = "rash", dept = "NONIT", sal = "7000" }
};
var query = (from dynamic stud in pairs
             group stud by stud.dept into grps
             select new { 
                 IT = grps.Count(stud => stud.dept == "IT"), 
                 NONIT = grps.Count(stud => stud.dept == "NONIT") 
             });

我在这里得到ITNONIT计数,但我得到两行结果,每组都是分别查询。我可以一次性计算它们吗?如果我像下面那样循环查询,那么我得到的输出是2,0和0,2

foreach (dynamic result in query)
{
    Console.WriteLine(result.IT + "," + result.NONIT);
}

这是因为每个组都是单独查询。我正在寻找像2,2的结果。 这可能吗?

1 个答案:

答案 0 :(得分:1)

如果您确切知道部门名称是“IT”或“NONIT”,结果应该是单个数据,您可以获得预期的输出而不进行分组:

var result2 = new
              {
                  IT = (from dynamic stud in pairs where stud.dept == "IT" select stud).Count(),
                  NONIT = (from dynamic stud in pairs where stud.dept == "NONIT" select stud).Count()
              };
Console.WriteLine(result.IT + "," + result.NONIT);

或者如果您喜欢分组,我建议将查询结果转换为字典,以便按部门名称轻松查找计数:

var query = (from dynamic stud in pairs
              group stud by stud.dept
              into grps
              select
                  new
                  {
                      Dept = grps.Key,
                      Count = grps.Count()
                  }).ToDictionary(o => o.Dept, o => o.Count);

Console.WriteLine(string.Format("result : {0}", query["IT"] + "," + query["NONIT"]));

如果以上都不符合您的要求,请更新问题以详细说明您的目标。