c#读取行并在字典中存储值
我想读取csv文件,并在字典中以正确的方式存储值c#读取行并在字典中存储值,c#,.net,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.S
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]) } });
}
}
}
使用(var reader=newstreamreader(@“CSV_testdaten.CSV”))
{
而(!reader.EndOfStream)
{
串新线;
while((new_line=reader.ReadLine())!=null)
{
var值=新的分割线(“,”);
g、 添加_顶点(值[0],新字典(){{values[1],Int32.Parse(值[2])});
}
}
}
“添加顶点”函数如下所示:
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;
}
字典顶点=新建字典();
public void add_顶点(字符串名称、字典边)
{
顶点[名称]=边;
}
csv文件如下所示:
g.add_vertex("0", new Dictionary<string, int>() { { "1", 731 } ,
{ "2", 1623 } , { "3" , 1813 } , { "4" , 2286 } , { "5" , 2358 } ,
{ "6" , 1 } , ... });
有多行具有相同的值[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 } , ... });
g.add_顶点(“0”,newdictionary(){{“1”,731},
{ "2", 1623 } , { "3" , 1813 } , { "4" , 2286 } , { "5" , 2358 } ,
{ "6" , 1 } , ... });
我想将具有相同ID的所有值(在csv文件的第一列中)添加到一个具有此ID的字典中。但我不确定如何执行此操作。有人能帮忙吗 当我们有复杂的数据并且想要查询它们时,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行:
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]);
}
}
}
}
通过您的输入,结果将是:
这对你有用吗
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));
如果您的add_vertex
方法(更习惯地称为AddVertex
,顺便说一句,最好尽早养成遵循命名约定的习惯)只需要接受一条边,为什么不将其更改为AddVertex(字符串名称,字符串边名称,int-edgeValue)
?(我刚刚猜到了参数名-我不知道边代表什么。)然后检查字典是否已经包含该顶点名称的条目,如果没有,则创建一个新值(也是字典)。无论哪种方式,都可以为该顶点将新条目添加到字典中。这对我来说非常有效。非常感谢。出于某种原因,我不得不在(“;”)上拆分csv中的行,但其他一切都很好。谢谢:)