Linq GroupBy和Sum在两个字段上 [英] Linq GroupBy and Sum over two fields

查看:120
本文介绍了Linq GroupBy和Sum在两个字段上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个三列表,我想按第一列和第二列进行分组,并对第三列求和.

Linq有可能吗?如果是这样,语法是什么,我找到了一个单列groupby,但看不到如何扩展它.

I''ve got a three column table, I would like to group by the first and second columns and sum the third.

Is this possible in Linq? If so what is the syntax, I''ve found for a single column groupby but can''t see how to expand it.

推荐答案

尝试一下, http://www.devcurry.com/2009/02/groupby-multiple-values- in-linq.html [ ^ ]或 http://msdn.microsoft.com/en-我们/library/bb534743.aspx [ ^ ]
Try this, http://www.devcurry.com/2009/02/groupby-multiple-values-in-linq.html[^] or this, http://msdn.microsoft.com/en-us/library/bb534743.aspx[^]


谢谢,我现在可以正常工作了:
Thanks, I''ve got that working now:
var query = feeAllRecords
    .GroupBy(f => new { f.AccountNo, f.FeeTypeID })
    .Select(group => new { fee = group.Key, total = group.Sum(f => f.FeeAmount) });



目前,我正在遍历此结果集以转换为最终结果集:



At the moment I''m then looping through this result set to convert to my final result set:

List<inFee> feeRecords = new List<inFee>(feeAllRecords.Capacity);
foreach (var rec in query)
{
    inFee fee2 = new inFee();
    fee2.AccountNo = rec.fee.AccountNo;
    fee2.FeeTypeID = rec.fee.FeeTypeID;
    fee2.FeeAmount = rec.total;

    feeRecords.Add(fee2);
}



它有效,但似乎不正确",或者至少应该有一种更有效的方法?



It works, but it seems ''incorrect'', or at least that there should be a more efficent method??


这篇关于Linq GroupBy和Sum在两个字段上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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