在c#中将文件文本解析为字典

时间:2018-05-02 01:09:46

标签: c# csv dictionary text nested

我的文本文件包含:

0,ke-2,0.0986089045676918
0,putar,0.141656526869241
1,film,0.110677581313152
1,aveng,0.12035192077391

我想将文件txt解析为具有以下结构的字典:

structure

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

how ca i fix it?

我该如何解决?

1 个答案:

答案 0 :(得分:2)

您的代码可能有效,但只适用于只有2个键(0&amp; 1)的情况,如果添加键2,一切都会中断

您可以将LINQGroupBy

一起使用

请参阅下面的代码

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