使用Linq对锯齿阵列(和,平均值,其他函数)执行列操作 [英] column operations on jagged arrays (sum, average, other functions) with Linq

查看:217
本文介绍了使用Linq对锯齿阵列(和,平均值,其他函数)执行列操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有相同长度的项目数组交错数组(即忽略范围赶上了):

  INT [] [] jaggedArray =新INT [] [] 
{
新INT [] {1,3,5},
新INT [] {0,2,4},
新INT [] {} 11,22,6
};



什么是运用C#LINQ到执行列操作最优雅的方式。示例结果简单的列运算总和与平均值:



总和()列结果:INT [] {12,27,15}
平均值()列结果:INT [] {4,9,5}
...这列上运行任何其他类似的扩展方法



最近相关的问题我可以发现是这里



感谢您的答案,我已经接受了周杰伦的答案,还贴列的相似,但更为复杂的聚集在一个可枚举问题的这里


解决方案

 变种结果= Enumerable.Range(0,jaggedArray [0]。长度)
。选择(ⅰ= GT; jaggedArray.Sum(一个=>一种由[i]))
.ToArray();



替换总和平均


Assuming we have a jagged array with equal length item arrays (i.e. ignore catching out of ranges):

int[][] jaggedArray = new int[][] 
{
    new int[] {1, 3, 5},
    new int[] {0, 2, 4},
    new int[] {11,22,6}
};

what is the most elegant way to apply c# Linq to perform column operations. Example results for simple column operations Sum and Average:

Sum() column result: int[] {12, 27, 15 } Average() column result: int[] {4, 9, 5 } ...any other similar extension method that operates on a column.

The closest related question I could find is here.

Thanks for the answers, I have accepted Jay's answer and also posted a similar but much more complicated aggregation of columns on an Enumerable question here.

解决方案

  var results = Enumerable.Range(0, jaggedArray[0].Length)
    .Select(i => jaggedArray.Sum(a => a[i]))
    .ToArray();

Substitute Sum with Average etc.

这篇关于使用Linq对锯齿阵列(和,平均值,其他函数)执行列操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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