【问题标题】:How to make jagged array to 2D array C# [closed]如何将锯齿状数组制作为二维数组 C# [关闭]
【发布时间】:2016-04-05 20:39:53
【问题描述】:

我想将具有不同列长度的 2D 锯齿状数组制作为具有相等列长度的 2D 数组。 我尝试将int[][] 转换为List<List<int>>。 例如, 我该怎么做

int[][] = 
{0,1,1},
{1,1,1,1},
{1,1,1,1},
{0,1,1}

收件人

int[][] = 
{0,1,1,0},
{1,1,1,1},
{1,1,1,1},
{0,1,1,0}  // (inserting 0 to extended space)

【问题讨论】:

  • 我想,你已经尝试了一些东西。您从哪里得到错误?
  • 这是一个很好的要求。你有什么问题?
  • 我将 [][] 更改为嵌套 List 并在 row[column].Count 小于最大数组大小时添加“0”。它以这种方式工作,但是,我的代码看起来不是很干净。我想知道是否有更清洁的方法来实现这一点。
  • 你能把你用过的代码贴出来吗?
  • 另外,您能否更新您的问题以说明您已将数据类型更改为List<List<int>>

标签: c# arrays multidimensional-array jagged-arrays


【解决方案1】:

您在两次都使用int[][],而不是替代int[,],因此我将忽略术语并假设您只想填充0以使所有内容长度相同:

int[][] arr = ...

int maxLength = arr.Max(x => x.Length);
var arr2 = arr.Select(x =>
                      {
                          if (x.Length == maxLength)
                              return x;
                          var y = new int[maxLength];
                          x.CopyTo(y, 0);
                          return y;
                      }).ToArray();

// now arr2 is the same as arr but with uniform lengths and padded 0's at the end

这种方法执行许多分配。另一种方法是:

List<List<int>> lists = ...

// with linq:
int maxLength = lists.Max(x => x.Count);

// without-linq:
int maxLength = 0;
foreach (var list in lists)
    if (list.Count > maxLength)
        maxLength = list.Count;
// end without-linq

foreach (List<int> list in lists)
    while (list.Count < maxLength)
        list.Add(0);

选择你更喜欢的,更适合你的情况。

您也可以避免在第一种方法中使用 Linq(如果您愿意的话),但我没有为那个方法费心。

【讨论】:

    【解决方案2】:

    这样的事情对你有用吗?

    List<List<int>> jagged = ...
    
    var maxLen = jagged.Max(x => x.Count);
    for (var i=0; i<jagged.Count; i++){
        while (jagged[i].Count < maxLen) jagged[i].Add(0);
    }
    

    dotnetfiddle

    【讨论】:

    • 如果遇到错误,您需要包含 System.Linq。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2011-02-04
    • 2015-06-28
    相关资源
    最近更新 更多