CSV文件转换为二维数组 [英] CSV file into two dimensional array
本文介绍了CSV文件转换为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
新手C#程序员在这里(3个月)
我的CSV文件如下所示:
0,1,2,3
4,5,6,7
8,9,10,11
12,13,14,15
16,17,18,19
20,21,22,23
如何将其编码为2D数组?
我的尝试:
Newbie C# programmer here (3 months)
My CSV file looks like this:
0,1,2,3
4,5,6,7
8,9,10,11
12,13,14,15
16,17,18,19
20,21,22,23
How do I code this into a 2D array?
What I have tried:
StreamReader stream = null;
string line;
string[] fields;
// open the file for reading; assumes file exists
stream = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
while (!stream.EndOfStream) // while there is still data in the file
{
line = stream.ReadLine(); // read next line with product data
part = line.Split(','); // split into fields using comma as delimiter
for (int i = 0; i < part.GetLength(0); i++)
{
list[i, 0] = part[i];
for (int j = 0; j < list.GetLength(1); j++)
{
list[0, i] = part[i];
}
}
lst.Items.Add(list);
推荐答案
我认为你在这里需要的是一个锯齿状的数组。锯齿状数组是一个数组数组。
I think that what you may need here is a jagged array. A jagged array is an array of arrays.
string fileName = @"C:\temp\myfile.txt";
string[] lines = File.ReadAllLines(fileName);
int[][] jaggedArray = new int[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
string[] strArray = lines[i].Split(',');
int[] intArray = Array.ConvertAll(strArray, int.Parse);
jaggedArray[i] = intArray;
}
string result = string.Join(", ", jaggedArray[0]);
Console.WriteLine(result);//0,1,2,3
这篇关于CSV文件转换为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文