[英]Parse file text to dictionary in c#
我有包含的文本文件:
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;
}
我該如何解決?
您的代碼可能會起作用,但是它僅在只有2個鍵(0和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])));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.