创建字符串2 dim数组以从C#中的csv文件复制数据 [英] Create string 2 dim array to copy the data from the csv file in C#
本文介绍了创建字符串2 dim数组以从C#中的csv文件复制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hello, couldn't you please advise me how to create a string 2 dimensional array and copy there the data from the csv file. This code is not creating string data[,] array and do not copy the data from the csv file in the loop.
我尝试过:
What I have tried:
using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using lpsolve55;
namespace LpSolveExample
{
class Program
{
static void Main(string[] args)
{
int n = 158;
int m = 9;
string[,] data = new string[n, m];
string path = "D:\\NM1997.csv";
StreamReader sr = new StreamReader(path);
int i = 0, j = 0;
string line; string temp;
char delim = ';';
string[] mass_t;
while (((line) = sr.ReadLine()) != null)
{
mass_t = line.Split(';');
while (j < mass_t.Length)
{
temp = mass_t[j];
data[i, j] = (temp);//this does not work
j++;
}
i++;
}
for(int k=0;k>158; k++)
{
for(int l =0;l<9;l++)
{
Console.Write(data[i, j]);
Console.WriteLine();
}
}
}
}
}
推荐答案
而不是使用而
用于内循环,而使用代替
:
Instead of using awhile
for your inner loop, use afor
:
while (!sr.EndOfStream)
{
line = sr.ReadLine();
mass_t = line.Split(';');
for (int i = 0; j < mass_t.Length; j++)
{
temp = mass_t[j];
data[i, j] = temp;
}
i++;
}
或者更好,使用File.ReadAllLines将它们全部读入字符串数组,并使用 foreach
在那个阵列上。
比使用快速CSV阅读器 [ ^ ]也将处理引用的字符串。它可以配置为使用;而不是,作为分隔符。
Or better, use File.ReadAllLines to read them all into an array of strings, and use foreach
on that array.
Even better than that though would be to use A Fast CSV Reader[^] which will handle quoted strings as well. It can be configured to use ";" instead of "," as the separator.
这篇关于创建字符串2 dim数组以从C#中的csv文件复制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文