我有一个包含13个数字的列表,我想将它们相乘

时间:2017-01-31 09:53:05

标签: c# linq

我有一个字符numbers,其中包含13个数字,例如:

string numbers = "01234567890123456781";

我必须乘以

0 * 1 * 2 * 3 * ... * 7 * 8 * 1 

我已经找到了添加数字的解决方案:

0 + 1 + 2 + 3 + ... + 7 + 8 + 1

我将number字符串转换为List<int> numb,然后在 Linq Sum()方法的帮助下对列表中的项目求和:

        string numbers = "01234567890123456781";
        List<int> numb = new List<int>();

        for (int i = 0; i < numbers.Length; i++)
        {
            int num = int.Parse(numbers[i].ToString());
            numb.Add(num);
        }

        for (int b = 0; b <numb.Count()-12; b++)
        {
            var x = numb.Skip(b).Take(13);
            int a = x.Sum(); // <- it's easy to sum, but what shall I do to multiply?
            Console.WriteLine(a);
        }

但是, Linq 没有任何Mult()或类似的方法,那么我可以做些什么来项目相乘?

1 个答案:

答案 0 :(得分:3)

如果numbers仅包含数字[0..9],则只需使用简单的 Linq

  // since 0 * anything == 0, I've removed all 0's to obtain non-zero result:
  // 1 * 2 * 3 * ... * 7 * 8 * 1 
  string numbers = "123456789123456781";

  // long: int is not large enough
  long result = numbers
    .Select(c => (long) (c - '0'))
    .Aggregate((s, a) => s * a);

结果:

  // 14631321600
  Console.Write(result);

Aggregate(自定义聚合)如果您要将IEnumerable<T>.Sum()从求和(如当前代码中)更改为乘法,则会执行此操作:

  ...
  var x = numb.Skip(b).Take(13); //TODO: get rid of magic number 13
  // instead of summation
  // int a = x.Sum();
  // let's use multiplication as a custom aggregation:
  // please, mind overflow: int is not enough when multiplying items
  long a = x
    .Select(item => (long) item) 
    .Aggregate((s, item) => s * item);