2010-07-04 63 views
6

在交易对象列表中,我尝试按BatchNo进行分组,然后对Amounts进行求和。C#LINQ to Objects:Group By/Sum help

public class Extract 
{ 
    // Notable fields in TRANSACTION are: String mBatchNo, String mAmount 
    private List<Transaction> Transactions; 

    public void testTransactions() 
    { 

     // Sum of amounts grouped by batch number 
     var sGroup = from t in Transactions 
        group t by t.mBatchNo into g 
        select new { batchNo = g.Key, 
            totalAmount = g.Max(a => (Int32.Parse(a.mAmount)))}; 
    } 
} 

在这一点上,我踏进代码去翻当地人窗户看我的结果集就是要检查我已经导入到该对象的文件。

文件中的最后一批有3条记录,每条记录100条,可以看到钻入事务列表对象。然而,深入到sGroup结果中发现相同的批次总共有100个数量(应该是300)。我在这个查询中搞砸了什么?

请注意,我将它存储为字符串,因为我们将零填充到8个字符字段的左侧。出于出口的原因,我决定将其存储为字符串。虽然这可以(也可能会改变),但它不能回答我的问题:如何使这个查询将总和汇总到由BatchNo设置的集合中?

回答

16

你需要调用Sum而不是Max

var sGroup = from t in Transactions 
    group t by t.mBatchNo into g 
    select new { 
     batchNo = g.Key, 
     totalAmount = g.Sum(a => (int.Parse(a.mAmount))) // Sum, not Max 
    }; 

我也建议,如果您的mAmount字段被存储为string,使用更可靠的方法比int.Parse(因为这将抛出一个异常如果该字符串不是有效的整数,例如,如果它是空白的)。这样的事情:

int ParseOrZero(string text) 
{ 
    int value; 
    if (int.TryParse(text, out value)) 
     return value; 
    else 
     return 0; 
} 

var sGroup = from t in Transactions 
    group t by t.mBatchNo into g 
    select new { 
     batchNo = g.Key, 
     totalAmount = g.Sum(ParseOrZero) // blanks will be treated as 0 
    }; 
+0

哇这是一个looooong周末,我错过了!感谢您的异常输入! – Mohgeroth 2010-07-04 20:49:40

2

而不是做最大你应该使用你的组的总和。现在,您只将属性设置为对象中的最大值,sum将对属性中的所有值进行求和。