【问题标题】:Can't use sum in anonymous type不能在匿名类型中使用 sum
【发布时间】:2019-08-02 14:32:50
【问题描述】:

我不能在 LINQ 中使用 Sum() 函数。

var results = _resultTable.AsEnumerable()
           .Select(x => new
            {
                AccountId = x["AccountID"],
                SubAccountId = x["SubAccount"],
                Amount = x["Amount"]
            })
            .GroupBy(s => new { s.AccountId, s.SubAccountId })
            .Select(x => new
            {
                x.Key.AccountId,
                x.Key.SubAccountId,
                TotalAmount = x.Sum(g => g.Amount)
            });

我无法编译它给出错误的代码

无法将类型“object”隐式转换为“long?”。明确的 存在转换(您是否缺少演员表?)

无法将 lambda 表达式转换为预期的委托类型,因为 块中的某些返回类型不可隐式转换 到委托返回类型

【问题讨论】:

  • 我认为你可以这样做:x.Sum(g => (long) g.Amount) ...虽然不确定。

标签: c# linq


【解决方案1】:

我认为这是 Linq-To-DataTable 并且您没有将对象转换为正确的类型。你不能Sum 对象。所以你需要这样的东西(注意DataRow.Field<int>(..)):

.Select(x => new
        {
            AccountId = x["AccountID"],     // you should also cast
            SubAccountId = x["SubAccount"], // you should also cast
            Amount = x.Field<int>("Amount") // int you can sum, Object not
        })
        // rest

你也可以在最后施放,但我不喜欢事后解决一个烂摊子,最好防止它:

// ...
.Select(grp => new
        {
            grp.Key.AccountId,
            grp.Key.SubAccountId,
            TotalAmount = grp.Sum(x => (int)x.Amount)
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多