读取CSV文件并将其保存到对象/列表中

时间:2015-07-23 18:20:48

标签: c# csv

DateTime,2048,2049,2050,2051 23/07/2015 8:57:30 AM,0,-30972,-31049,-21068 23/07/2015 8:57:32 AM,0,-30970,-31047,-21066 23/07/2015 8:57:35 AM,0,-30967,-31044,-21063 23/07/2015 8:57:37 AM,0,-30965,-31042,-21061 23/07/2015 8:57:40 AM,0,-30962,-31039,-21058 23/07/2015 8:57:43 AM,0,-30960,-31036,-21055 23/07/2015 8:57:45 AM,0,-30957,-31034,-21053 23/07/2015 8:57:52 AM,0,-30949,-31026,-21045 23/07/2015 8:57:55 AM,0,-30947,-31024,-21043

您好,我正在尝试将每列保存到并发字典中。

我有一个并发字典。

ConcurrentDictionary<int, int[]> fileLoading = new ConcurrentDictionary<int, int[]>();

我想尝试将每个列标题保存为键,我想将列中的所有值保存到int数组中。

列标题未固定,因为标题确实会更改为不同的值。

此外,我还希望将日期/时间保存到列表中。

List<string[]> timeCol = new List<string[]>();

完成后,我想使用字典将其显示在图表中,因为我需要在显示之前对它们进行一些操作,并在第一列中显示日期时间。

List<string[]> rows = File.ReadAllLines(filepath).Select(x => x.Split(',')).ToList();
DataTable loadedValues = new DataTable();
        ConcurrentDictionary<int, int[]> fileLoading = new ConcurrentDictionary<int, int[]>();

        rows.ForEach(x =>
        {
            try 
            { 
                loadedValues.Rows.Add(x);


            }
            catch { Console.WriteLine("Value not compatable"); }
        });

这是我到目前为止所做的,但这只是保存到一个数据表,我想要一个并发的字典列表,而不是做一些特定的操作。 谢谢

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。下面是一个示例,说明如何遍历已解析的行以填充ConcurrentDictionary

// Parse
var rows = File.ReadAllLines(filePath).Select(l => l.Split(',')).ToArray();

ConcurrentDictionary<int, int[]> fileLoading = new ConcurrentDictionary<int, int[]>();

// Iterate through each column (skipping the date column)
for (int c = 1; c < rows[0].Length; c++)
{  
    // Column header
    int column = Int32.Parse(rows[0][c]);

    // Column values
    fileLoading[column] = rows.Skip(1).Select(r => Int32.Parse(r[c])).ToArray();
}
相关问题