【问题标题】:C# How to use BigInteger with this Lambda expression?C# 如何在这个 Lambda 表达式中使用 BigInteger?
【发布时间】:2011-03-20 20:14:09
【问题描述】:

var totalCost = Persons.Sum(x => BigInteger.Parse(x.cost.First(kv => kv.Key == "volvo").Value))

错误:
无法将 lambda 表达式转换为委托类型“System.Func< Persons,int >” 因为块中的某些返回类型不能隐式转换为委托返回类型。
无法将类型“System.Numerics.BigInteger”隐式转换为“int”。 存在显式转换(您是否缺少演员表?)

我已经将它与OrderByDescending 一起使用,它工作正常。我可以理解错误。我只是不知道用什么替换Sum 才能使它工作。

如何正确使用BigInteger 和该语句?

【问题讨论】:

    标签: c# lambda biginteger


    【解决方案1】:

    从本质上讲,Sum 方法的重载无法与 .NET 4.0 中的 BigInteger 一起使用。您可以自己编写一个重载,或者使用更通用的Aggregate 运算符进行求和:

    var totalCost = Persons.Select(x => BigInteger.Parse(x.cost.First(kv => kv.Key == "volvo").Value))
                           .Aggregate(BigInteger.Zero, (sum, next) => sum + next);
    

    【讨论】:

      【解决方案2】:

      很遗憾,你不能。 Sum 没有过载 BigInteger,因此您必须自己进行求和。

      不过,您始终可以编写自己的扩展方法:

      public static class EnumerableExtension
      {
          public static BigInteger Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, BigInteger> selector)
          {
              BigInteger output = 0;
      
              foreach(TSource item in source)
              {
                  output += selector(item);
              }
      
              return output;
          }
      }
      

      只要此类在您的using 命名空间之一内,您现在就可以按照您的要求调用Sum

      【讨论】:

        【解决方案3】:

        您可以使用Aggregate

        //written without an IDE...
        var bigIntegerSum = Persons.Aggregate( (sum, next) => sum + next);
        

        【讨论】:

          【解决方案4】:

          基于您的变量名为“totalCost”这一事实,我猜测您正在处理金钱,在这种情况下,decimal 是比BigInteger 更好的类型。由于decimalSum 有一个重载,所以如果你使用它会起作用:

          var totalCost = Persons.Sum(x =>
                               Decimal.Parse(x.cost.First(kv => kv.Key == "volvo").Value))
          

          【讨论】:

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