如何在LINQ中使用自定义聚合函数? (不使用扩展方法) [英] How to use self defined aggregate function with LINQ? (without using extension methods)

查看:75
本文介绍了如何在LINQ中使用自定义聚合函数? (不使用扩展方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在问题中计算使用LINQ 从1到n的数字,函数sum是预先存在的,那么当我们要定义自己的函数时呢?例如SquareSum函数(要在其中加上数字的平方)或其他一些不存在的函数?

In the question Calculate the sum of numbers from 1 to n using LINQ, the function sum was preexisting, what about when we want to define our own function ? for example SquareSum function, where the the square of numbers are to be added, or some other non preexisting function?

评论了扩展方法的使用,我实际上是在寻找一种不用扩展方法的方法.

Edit : the use of extension method was commented, I was actually looking for a way to do it without extension methods.

推荐答案

您可以这样写

IEnumerable<int> range = Enumerable.Range(1, n);
var sum = range.Aggregate(0, (x, y) => x + y);

平方和:

IEnumerable<int> range = Enumerable.Range(1, n);
var sum = range.Aggregate(0, (x, y) => x + y * y);

这篇关于如何在LINQ中使用自定义聚合函数? (不使用扩展方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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