使用C#将CSV转换为多维数组

3
如何将CSV文件读入多维数组?
public void CSV_ToArray(string filePath)
    {
        try
        {
            StreamReader sr = new StreamReader(filePath);
            int colCount = 3;
            int rowCount = getNumberOfRows(sr);

            string[,] Contacts = new string[rowCount, colCount];
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
        }

    }

我已经创建了数组及其维度,但不确定如何将数据分配到数组中的每个位置。
CSV文件的格式将是: 名字,姓氏,电子邮件。

使用正确的工具。请查看 Microsoft.VisualBasic.FileIO.TextFieldParser - Sam Axe
我宁愿将其读入 DataTable。 - Uwe Keim
2个回答

3

评论中指出最好使用预定义库,可能解析成 DataTable

如果您不介意使用嵌套数组而不是二维数组,则考虑以下一行代码:

string[][] lines = File.ReadLines(path)
          .Select(s => s.Split(",".ToCharArray())).ToArray().ToArray();

你可以使用lines[1][3]而不是lines[1,3]来访问它。

在您的情况下,也许创建一个类会更好:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }

    public Contact(string firstName, string lastName, string emailAddress)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.EmailAddress = emailAddress;
    }

    public static Contact[] LoadContacts(string csvFile)
    {
        return File.ReadLines(csvFile).Select(CreateFromCsvLine).ToArray();
    }
    private static readonly char[] separator = new[] { ',' };
    private static Contact CreateFromCsvLine(string line)
    {
        string[] split = line.Split(separator);
        return new Contact(split[0], split[1], split[2]);
    }
}

在这种情况下,您可以这样做:

Contact[] contacts = Contact.LoadContacts("contacts.csv");
string name = contacts[0].LastName;

在这种情况下,第二行可以通过 string name = contacts[1].LastName; 访问? - Graham Warrender
@GrahamWarrender 是的,确实。 - Bas

3
您可以添加一个方法,该方法接收路径和分隔符,并准备返回string[][]。例如:
using System.IO;

public static string[][] CSV_ToArray(string path, string separator = ";")
{
    // check if the file exists
    if (!File.Exists(path))
        throw new FileNotFoundException("The CSV specified was not found.");

    // temporary list to store information
    List<string[]> temp = new List<string[]>();

    using (var reader = new StreamReader(File.OpenRead(path)))
    {
        while (!reader.EndOfStream)
        {
            // read the line
            string line = reader.ReadLine();

            // if you need to give some changes on the inforation
            // do it here!
            string[] values = line.Split(separator.ToCharArray());

            // add to the temporary list
            temp.Add(values);           
        }
    }

    // convert te list to array, which it will be a string[][]
    return temp.ToArray();  
}

并使用它:

string[][] csv = CSV_ToArray("myFile.csv");

或者使用另一个分隔符:
string[][] csv = CSV_ToArray("myFile.csv", ",");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接