C#LINQ to Objects:Group By/Sum帮助

Moh*_*oth 6 c# linq-to-objects

在事务对象列表中,我尝试按BatchNo进行分组,然后对Amounts进行求和.

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)))};
    }
}
Run Code Online (Sandbox Code Playgroud)

此时,我通过locals窗口进入代码查看,看看我的结果集是针对我导入到此对象的文件进行检查的.

文件中的最后一批有3条记录,每条记录100个,可以看到钻入到事务列表对象中.但是向下钻取到sGroup结果会发现同一批次总数为100(应为300).我在这个查询中搞砸了什么?

请注意,我已将其存储为字符串,因为我们在8字符字段的左侧填零.出于出口原因,我决定将其存储为字符串.虽然这可以(也可能会)改变,但它没有回答我的问题:如何使这个查询通过BatchNo将总和聚合成集合?

Dan*_*Tao 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
    };
Run Code Online (Sandbox Code Playgroud)

我还建议,如果你的mAmount字段存储为a 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
    };
Run Code Online (Sandbox Code Playgroud)