c# / Linq sum where
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14561312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# / Linq sum where
提问by Gordon Copestake
I have a table NCR containing data of the format:
我有一个包含以下格式数据的表 NCR:
ID | Date | Item | Type | Qty
1 | 01/01/13 | Apple | A | 1
2 | 01/01/13 | Apple | B | 1
3 | 01/01/13 | Orange | C | 1
4 | 01/01/13 | Orange | A | 2
6 | 01/01/13 | Orange | C | 1
I would like to produce a linq query that gives me a summary of the types and sums for a given date like so:
我想生成一个 linq 查询,它为我提供给定日期的类型和总和的摘要,如下所示:
Item | A | B | C
Apple | 1 | 1 | 0
Orange | 2 | 0 | 2
So far I have this:
到目前为止,我有这个:
var q = data.GroupBy(l => l.Item)
.Select(g => new {
Item = g.Key,
Total = g.Sum(c => c.Qty),
A = g.Sum(c => c.Type == "A"),
B = g.Sum(c => c.Type == "B"),
C = g.Sum(c => c.Type == "C")
});
However I can't seem to give a criteria to the g.Sum lambda statement. If I use Count (which is the wrong data) I can give the critera, but why is Sum missing this? What is my alternative to creating a summary table of the data available?
但是,我似乎无法为 g.Sum lambda 语句提供标准。如果我使用 Count(这是错误的数据),我可以给出标准,但是为什么 Sum 会遗漏这个?除了创建可用数据的汇总表之外,我还有什么替代方法?
采纳答案by Jon Skeet
The delegate provided to Sum
isn't a predicate; it's a selector.
提供给的委托Sum
不是谓词;这是一个选择器。
Are you trying to sum the Qty
property? If so, I suspect you want:
你想对Qty
财产求和吗?如果是这样,我怀疑你想要:
A = g.Where(c => c.Type == "A").Sum(c => c.Qty),
B = g.Where(c => c.Type == "B").Sum(c => c.Qty),
C = g.Where(c => c.Type == "C").Sum(c => c.Qty)
(Or you could group by type as well, of course.)
(当然,您也可以按类型分组。)