用LINQ计算产品 [英] Calculate product with LINQ

查看:69
本文介绍了用LINQ计算产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习LINQ,并且有一个非常简单的问题,我认为它将帮助我更好地理解该技术.如何找到一个整数数组的乘积?

I am learning LINQ and have a very simple question that I think will help my understand the technology better. How can I find the product of an array of ints?

例如,LINQ的工作方式是什么:

For example, what is the LINQ way to do:

int[] vals = { 1, 3, 5 };
return vals[0] * vals[1] * vals[2];

推荐答案

这将起作用:

var product = vals.Aggregate(1, (acc, val) => acc * val);

您从1的种子开始,然后使用两个参数为每个值调用该函数,其中acc是当前的累加值,而val是数组中的值;该函数将当前累加值乘以数组中的值,然后将该表达式的结果作为acc传递给下一个函数.即,您提供的数组的函数调用链为:

You're starting with a seed of 1 and then the function is called for each of your values with two arguments, acc which is the current accumulated value, and val which is the value in the array; the function multiplies the current accumulated value by the value in the array and the result of that expression is passed as acc to the next function. i.e. the chain of function calls with the array you provided will be:

(1, 1) => 1
(1, 3) => 3
(3, 5) => 15

这篇关于用LINQ计算产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆