使用LINQ to获取与自定义对象列表的总和/平均 [英] Using LINQ to Get Sum/ Average of a List with custom objects
问题描述
我有一个类:
public class PointD
{
public double X
{ get; set; }
public double Y
{ get; set; }
public PointD(double x, double y)
{
X = x;
Y=y;
}
//operator for +,-, * and / are overridden
}
给定一个列表< PointD>
,如何获得它的使用LINQ的平均? A 为
循环相当于将是这样的:
Given a list<PointD>
, how to get the average of it using LINQ? A for
loop equivalent will be something like this:
double xx, yy;
for ( int i=0; i< ptlist.Count; i++)
{
xx+=ptlist[i].X;
yy+=ptlist[i].Y;
}
return new PointD(){X=xx, Y=yy};
您只可以使用任何的内置 LINQ功能。您不能定义一个扩展,采用此功能的照顾。
You can use any built-in LINQ function only. You can't define an extension that takes care of this function.
任何想法?
编辑:当然,你可以使用两个单独的总和
扩展方法将它们合并之前总和X和Y的组成部分。但是,这不是我想要的。我要的是一个单一的查询/方法,没有工作
Of course, you can use two separate Sum
extension method to Sum for X and Y component before merging them. But this is not what I want. What I want is a single query/ method that does the job
推荐答案
的汇总
函数将在这里派上用场。
The Aggregate
function would come in handy here.
var sum = list.Aggregate((acc, cur) => acc + cur);
var average = list.Aggregate((acc, cur) => acc + cur) / list.Count;
只是确保你有 /
运营商对于类型 PointD
和 INT
,这应该做的工作。
Just insure that you have the /
operator defined for types PointD
and int
, and this should do the job.
请注意:我不是很确定是否要求和或平均这里(你的问题是关于这个有些模棱两可的),但我已经包含了两个例子
Note: I'm not quite sure whether you want the sum or average here (your question is somewhat ambiguous about this), but I've included examples for both.
这篇关于使用LINQ to获取与自定义对象列表的总和/平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!