初始化交错数组的LINQ路 [英] Initialize a Jagged Array the LINQ Way

查看:118
本文介绍了初始化交错数组的LINQ路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维交错数组(虽然它总是矩形),我初始化采用传统的循环:

  VAR myArr,该=新的双[rowCount等] [];
的for(int i = 0; I< rowCount时,我++){
    myArr,该由[i] =新的双[colCount]
}

我想,也许有些LINQ功能都会给我一种优雅的方式在一个语句来做到这一点。不过,我可以拿出最接近的是这样的:

 双击[] [] myArr,该= Enumerable.Repeat(新双[colCount],rowCount等).ToArray();

问题是,它似乎已创造了一个单一的双击[colCount] 并分配为每行一个新的数组的intsead分配引用。有没有办法做到这一点没有得到太神秘?


解决方案

 双击[] [] myArr,该=可枚举
  .Range(0,rowCount等)
  。选择(I =>新建双[colCount])
  .ToArray();

I have a 2-dimensional jagged array (though it's always rectangular), which I initialize using the traditional loop:

var myArr = new double[rowCount][];
for (int i = 0; i < rowCount; i++) {
    myArr[i] = new double[colCount];
}

I thought maybe some LINQ function would give me an elegant way to do this in one statement. However, the closest I can come up with is this:

double[][] myArr = Enumerable.Repeat(new double[colCount], rowCount).ToArray();

The problem is that it seems to be creating a single double[colCount] and assigning references to that intsead of allocating a new array for each row. Is there a way to do this without getting too cryptic?

解决方案

double[][] myArr = Enumerable
  .Range(0, rowCount)
  .Select(i => new double[colCount])
  .ToArray();

这篇关于初始化交错数组的LINQ路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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