我的文本文件包含:
0,ke-2,0.0986089045676918 0,putar,0.141656526869241 1,film,0.110677581313152 1,aveng,0.12035192077391
我想将文件txt解析为具有以下结构的字典:
private Dictionary<int, Dictionary<string, double>> openNormalization()
{
var temp = new Dictionary<int, Dictionary<string, double>>();
var file = File.ReadLines("normalization.txt").Cast<string>();
foreach (string f in file)
{
var doc = new Dictionary<string, double>();
string fwd = "0";
string[] entry = f.Split(',');
if (entry[0] == fwd)
{
doc.Add(entry[1], Convert.ToDouble(entry[2]));
fwd = entry[0];
}
else
{
temp.Add(int.Parse(fwd), doc);
doc = new Dictionary<string, double>();
doc.Add(entry[1], Convert.ToDouble(entry[2]));
fwd = entry[0];
}
return temp;
}
我该如何解决?
答案 0 :(得分:2)
您的代码可能有效,但只适用于只有2个键(0&amp; 1)的情况,如果添加键2
,一切都会中断
您可以将LINQ
与GroupBy
请参阅下面的代码
private Dictionary<int, Dictionary<string, double>> openNormalization()
{
var lines = File.ReadLines("normalization.txt");
return lines
.Select(line => line.Split(','))
.GroupBy(item => Convert.ToInt32(item[0]))
.ToDictionary(groupValues => groupValues.Key, groupValues => groupValues.ToDictionary(item => item[1], item => Convert.ToDouble(item[2])));
}