从文件中读取2D矩阵到C#中的2D int数组 [英] Read 2D matrix from file to 2D int array in C#
问题描述
我在从文件读取2D文本并将其导入到 int 数组时遇到问题.具体来说,我的文本文件如下所示:
I have problem in reading 2D text from file and import it to an int array. Specifically, my text file looks like below:
2,3,4,5,6
2,3,4,5,6
5,2,3,4,5
5,2,3,4,5
2,4,6,7,4
2,4,6,7,4
2,7,8,5,6
2,7,8,5,6
因此,矩阵中的每个单元格均以逗号分隔,并且每一行都以新行开头.
So each cell in matrix is separated by comma and each new row starts with new line.
我尝试了多种方法使其有效,但我做不到!简而言之,我想在末尾使用 int [] []
或 int [,]
数组.
I tried many ways to make it works but I can't! Simply, I want an int[][]
or int[,]
array at the end.
P.S:我可以简单地将
P.S: I can read 1-D matrix simply to int[]
as below:
int[] array= File.ReadAllText(fileppath).Split(',').Select(t => int.Parse(t)).ToArray();
推荐答案
您首先需要将每行的索引添加到第一个维度,然后将行中的每个列"添加到第二个维度.
You first need to add the index of each line to the first dimension and then every 'column 'in the line to the second dimension.
尝试以下代码:
int[][] array = File.ReadAllText(filepath).Split('\n')
.Select(r => (r.Split(','))
.Select(c => int.Parse(c)).ToArray()).ToArray();
这篇关于从文件中读取2D矩阵到C#中的2D int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!