来自文本文件 c# 的二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13724781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:35:22  来源:igfitidea点击:

2d Array from text file c#

c#arraysfiletext2d

提问by ProgrammingRookie

I have a text file that looks like this

我有一个看起来像这样的文本文件

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100

in a 10 x 10 grid. using c# I need to take the text file and turn it into a 2d array of integers so that I can manipulate the integers on an independent level. Please help cant work it out,

在 10 x 10 的网格中。使用 c# 我需要获取文本文件并将其转换为二维整数数组,以便我可以在独立级别上操作整数。请帮助解决不了,

采纳答案by Esailija

String input = File.ReadAllText( @"c:\myfile.txt" );

int i = 0, j = 0;
int[,] result = new int[10, 10];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

The indices will be 0-basedso if you want to access 10thcolumn in fourthrow:

索引将从0 开始,因此如果您想访问第四行的第 10列:

Console.WriteLine(result[3,9]); //40

回答by Tim Schmelter

Perhaps:

也许:

var result = File.ReadLines(path)
    .SelectMany((l, i) => l.Split()
                           .Select(s => new int[] { i, int.Parse(s) })
                           .ToArray())
    .ToArray();

Edit: Although this is a jagged array int[][].

编辑:虽然这是一个锯齿状数组int[][]

回答by L.B

A jagged array?

锯齿状阵列?

int[][] list = File.ReadAllLines("a.txt")
                   .Select(l => l.Split(' ').Select(i => int.Parse(i)).ToArray())
                   .ToArray();

EDIT

编辑

You can use JaggedToMultidimensional here

你可以在这里使用 JaggedToMultiDimension

int[,] list2 = JaggedToMultidimensional(list);