Linq-分组并计数多个字段(单个总计输出) [英] Linq - Group by and count over multiple fields (output on single total)

查看:811
本文介绍了Linq-分组并计数多个字段(单个总计输出)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有查询答案的应用程序(50个字段,名称分别为upa1,upa2,upd1,upd6等,可能的值为"y","n"和"na").

I have an app with an inquiry answers (50 fields, with names like upa1, upa2, upd1, upd6, etc, with possible values "y", "n" and "na").

我可以使用以下方法获取并计数一个字段:

I can get and count one single field with this:

foreach(var y in items.GroupBy(g => g.upa1)
                      .Select(group => new {upa1name = group.Key, upa1count = group.Count()})) {
    <div>These are the totals for upa1:</div>
    <div>@y.upa1name : @y.upa1count</div>
}

它将输出以下内容:

These are the totals for upa1:
y : 30
n : 11
na : 18

我可以手动对所有问题重复此操作,但是我需要计算所有问题的"y","n"和"na"的数目以形成单个输出:

I can repeat this for all questions manually, but I need to count the number of "y", "n" and "na" for all questions to form this single output:

These are the totals for all questions:
y : 1342
n : 879
na : 445

我知道已经有关于这些问题的数百个主题,但是这些信息太过冗长,并且在此问题上有太多变化(不同的表,联接等).在多个字段的总和计数"上没什么.

I know there are already hundreds of topics about these issues, but the information is far too stretched and over way too many variations on this matter (different tables, joins, etc). Nothin on the "sum count over multiple fields".

谢谢.

此外,在旁注中,每行仅在答案至少存在一次的情况下才会出现,但是即使它是"y:0",我也需要显示它.这可能吗?

Also, on a side note, each line only appears if the answer exists at least once, but I need it to show even if it is a "y : 0". Is this possible?

推荐答案

只有三个可能的答案,您可以在三个单独的查询中进行此操作:

With only three possible answers you can do this in three separate queries:

foreach (var ans in new[] {"y", "n", "na"}) {
    var count = items.Sum(item =>
        (item.upa1==ans?1:0) + (item.upa2==ans?1:0) + (item.upd1==ans?1:0) + ...
    );
    <div>These are the totals for @ans:</div>
    <div>@ans : @count</div>
}

这应该运行得相当快.

这篇关于Linq-分组并计数多个字段(单个总计输出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆