c#Enumerable.Sum方法不支持ulong类型

时间:2016-02-24 21:00:40

标签: c# linq lambda

对于c#Enumerable.Sum<TSource> Method (IEnumerable<TSource>, Func<TSource, Int64>),我不支持ulong类型作为Mehtonf的返回类型,除非我将ulong转换为long

public class A
{
  public ulong id {get;set;}

} 




publec Class B
{
    public void SomeMethod(IList<A> listOfA)
    {
        ulong result = listofA.Sum(A => A.Id);
    }
}

compliler会抛出两个错误:

  1. enter image description here
  2. enter image description here

    除非我

  3. ulong result = (ulong)listOfA.Sum(A => (long)A.Id)

    无论如何在没有施法的情况下解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:13)

您可以改用Aggregate

ulong result = listOfULongs.Aggregate((a,c) => a + c);

或在您的具体情况

ulong result = listOfA.Aggregate(0UL, (a,c) => a + c.Id);

您还应该考虑是否真的应该首先使用无符号值类型。

答案 1 :(得分:5)

您可以编写自己的扩展方法来为ulong提供重载,因为它不是作为BCL的一部分提供的:

public static ulong Sum<TSource>(
    this IEnumerable<TSource> source, Func<TSource, ulong> summer)
{
    ulong total = 0;

    foreach(var item in source)
      total += summer(item);

    return total;
}
相关问题