[英]Can't use sum in anonymous type
I can't use Sum() function in LINQ. 我不能在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)
});
I can't compile code it gives errors 我无法编译会产生错误的代码
Cannot implicitly convert type 'object' to 'long?'. 无法将类型'object'隐式转换为'long?'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)
And 和
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type 无法将lambda表达式转换为预期的委托类型,因为该块中的某些返回类型不能隐式转换为委托返回类型
I think that's Linq-To-DataTable and you are not casting the objects to the correct type. 我认为那是Linq-To-DataTable,并且您没有将对象转换为正确的类型。 You can't Sum
objects. 您不能对对象Sum
。 So you need something like this(note the DataRow.Field<int>(..)
): 因此,您需要类似以下内容(请注意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
You could also cast at the end, but i don't like to fix a mess afterwards, better prevent it: 您也可以在最后进行投射,但是我不希望以后再搞乱,最好防止它:
// ...
.Select(grp => new
{
grp.Key.AccountId,
grp.Key.SubAccountId,
TotalAmount = grp.Sum(x => (int)x.Amount)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.