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

4
我希望读取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

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

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

我想将在CSV文件的第一列具有相同ID的所有值添加到一个具有该ID的字典中。但是我不确定如何做到这一点。有人能帮助吗?


1
如果你的 add_vertex 方法(顺便说一下,更常规的命名应该是 AddVertex,养成遵循命名规范的习惯是个好主意)只需要接受一个边,为什么不将其改为 AddVertex(string name, string edgeName, int edgeValue) 呢?(我只是猜测了参数名称 - 我无法确定这些边代表什么。)然后只需检查字典是否已经包含该顶点名称的条目,如果没有,则创建一个新值(也是一个字典)。无论哪种情况,都将新条目添加到该顶点的字典中。 - Jon Skeet
3个回答

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);

这对我来说完美无缺。谢谢!由于某种原因,我不得不在csv中将该行拆分为(";"),但其他一切都很好。谢谢 :) - Fehler40

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));

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


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