在C#从对象的不同实例阵列优雅平均 [英] Elegant averaging of arrays from different instances of an object in C#

查看:195
本文介绍了在C#从对象的不同实例阵列优雅平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相同的类型,每个都有一个属性,是浮筒的阵列的对象的列表。采取这一列表作为输入,什么是返回一个新的数组,它是该阵列的列表中的

的平均最简单的方法

输入对象是这样的:

 类MyDatas
{
    浮动[] DataValues​​;
}

...

名单< MyDatas> InputList;
浮动[]的结果;
 

的DataValues​​阵列将保证具有相同的长度。结果阵列的每个元素将是列表中的每个成员的阵列中的相应元件的平均值。例如:结果[0] =(InputList [0] .DataValues​​ [0] + InputList [1] .DataValues​​ [0] + ...)/ InputList.Count

当然,我可以蛮力与后内的一个foreach循环,然后for循环的另一股力量这一点,但在我看来,这应该是可行的LINQ的一行或两行。有什么建议?

解决方案

 浮法[]结果= inputList.Select(C => c.DataValues​​)
                          .Transpose()
                          。选择性(r => r.Average())
                          .ToArray();
 

使用转置的<一个href="http://stackoverflow.com/questions/2070356/find-common-$p$pfix-of-strings/2070434#2070434">here.

I have a list of objects of the same type that each has a property that is an array of floats. Taking this list as input, what is the easiest way to return a new array that is the average of the arrays in the list?

The input objects look like this:

Class MyDatas
{
    float [] DataValues;
}

...

List<MyDatas> InputList;
float [] result;

The DataValues arrays will be guaranteed to have the same length. Each element of the result array will be the average of the corresponding elements in the array of each member of the list. For example: result[0] = (InputList[0].DataValues[0] + InputList[1].DataValues[0] + ... ) / InputList.Count

Of course I could brute force this with a foreach inside a for loop and then another for loop after that but it seems to me this should be doable with one or two lines of LINQ. Any advice?

解决方案

float[] result = inputList.Select(c => c.DataValues)
                          .Transpose()
                          .Select(r => r.Average())
                          .ToArray();

using Transpose from here.

这篇关于在C#从对象的不同实例阵列优雅平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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