C#/ LINQ的总和,其中 [英] c# / Linq sum where

查看:182
本文介绍了C#/ LINQ的总和,其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有格式的表NCR包含数据:

I have a table NCR containing data of the format:

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 

我想产生一个LINQ查询,让我的种类和数额的摘要,像这样一个给定的日期:

I would like to produce a linq query that gives me a summary of the types and sums for a given date like so:

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

不过,我似乎无法给出一个标准的g.Sum拉姆达声明。如果我使用计数(这是错误的数据),我可以给性判据,但为什么总缺少呢?什么是我的替代方法来创建可用数据的汇总表?

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?

推荐答案

提供的总和的委托不是predicate;这是一个选择。

The delegate provided to Sum isn't a predicate; it's a selector.

您想求和的数量属性?如果是这样,我怀疑你想要的:

Are you trying to sum the Qty property? If so, I suspect you want:

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.)

这篇关于C#/ LINQ的总和,其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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