CSV 到多维数组与 c#

CSV to multidimensional array with c#

如何将 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 文件的格式为 名字、姓氏、电子邮件

评论解释说使用预定义的库可能会更好,并且可能会解析为 DataTable

如果您不介意锯齿状数组而不是二维数组,请考虑以下一行:

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

您可以使用 lines[1][3] 而不是 lines[1,3]

访问它

对于你的情况,也许为它创建一个 class 会更好:

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;

您可以添加一个接收路径和分隔符的方法,并将其准备为 return 和 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", ",");