C#读取行并将值存储在字典中

时间:2019-02-21 09:43:59

标签: c# .net

我想读取一个csv文件,并将值以正确的方式存储在字典中。

using (var reader = new StreamReader(@"CSV_testdaten.csv"))
{
    while (!reader.EndOfStream)
    {
        string new_line;
        while ((new_line = reader.ReadLine()) != null)
        {
            var values = new_line.Split(",");               
            g.add_vertex(values[0], new Dictionary<string, int>() { { values[1], Int32.Parse(values[2]) } });
        }
    }
}

add_vertex函数如下所示:

Dictionary<string, Dictionary<string, int>> vertices = new Dictionary<string, Dictionary<string, int>>();

    public void add_vertex(string name, Dictionary<string, int> edges)
    {
        vertices[name] = edges;
    }

csv文件如下所示:

enter image description here

有多行具有相同的值[0](例如,值[0]为“ 0”),而不是覆盖现有字典,而应将其添加到已存在值[0] = 0的字典中像这样:

    g.add_vertex("0", new Dictionary<string, int>() { { "1", 731 } , 
{ "2", 1623 } , { "3" , 1813 } , { "4" , 2286 } , { "5" , 2358 } ,
{ "6" , 1 } , ... });

我想将具有相同ID(在csv文件的第一列中)的所有值添加到具有此ID的一个词典中。但是我不确定该怎么做。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

当我们有复杂的数据并且想要查询时, Linq 可能会非常有帮助:

var records = File
  .ReadLines(@"CSV_testdaten.csv")
  .Where(line => !string.IsNullOrWhiteSpace(line)) // to be on the safe side
  .Select(line => line.Split(','))
  .Select(items => new {
     vertex = items[0],
     key    = items[1],  
     value  = int.Parse(items[2])  
   })
  .GroupBy(item => item.vertex)
  .Select(chunk => new {
     vertex = chunk.Key,
     dict   = chunk.ToDictionary(item => item.key, item => item.value)
  });

foreach (var record in records)
  g.add_vertex(record.vertex, record.dict);

答案 1 :(得分:2)

这对您有用吗?

vertices =
    File
        .ReadLines(@"CSV_testdaten.csv")
        .Select(x => x.Split(','))
        .Select(x => new { vertex = x[0], name = x[1], value = int.Parse(x[2]) })
        .GroupBy(x => x.vertex)
        .ToDictionary(x => x.Key, x => x.ToDictionary(y => y.name, y => y.value));

答案 2 :(得分:1)

您可以将代码分为两部分。首先将读取csv行:

public static IEnumerable<(string, string, string)> ReadCsvLines()
{
    using (var reader = new StreamReader(@"CSV_testdaten.csv"))
    {
        while (!reader.EndOfStream)
        {
            string newLine;
            while ((newLine = reader.ReadLine()) != null)
            {
                var values = newLine.Split(',');

                yield return (values[0], values[1], values[2]);
            }
        }
    }
}

第二秒钟会将这些行添加到字典中:

var result = ReadCsvLines()
    .ToArray()
    .GroupBy(x => x.Item1)
    .ToDictionary(x => x.Key, x => x.ToDictionary(t => t.Item2, t => int.Parse(t.Item3)));

输入result将是:

enter image description here