【问题标题】:Populate DataTable with nested dictionary result使用嵌套字典结果填充 DataTable
【发布时间】:2018-10-02 11:50:14
【问题描述】:

使用 C# 编码仅 2 个月:我有一个类型的字典结果: Dictionary<string, Dictionary<string, decimal>>

我已经能够控制台写成如下:

R&D Trainer 3000 Developer 6000 Consultant 0 Dev Trainer 0 Developer 4000 Consultant 5000

如您所见,内部字典具有相同的“键”。我试图通过以下方式将它们放入数据表中:

          var columns = l.GroupBy(d => d.Department, (key, items) => key).ToList();


        dt.Columns.Add("Function");
        foreach (var column in columns)
            dt.Columns.Add(column);
       foreach (var dict in result2)
        {

            Console.WriteLine(dict.Key );

                foreach (var dict2 in dict.Value)
                {

                    DataRow row2 = dt.NewRow();

                    row2["Function"] = dict2.Key;
                    row2[dict.Key] = dict2.Value;
                    dt.Rows.Add(row2);

                Console.WriteLine("  " + dict2.Key + "\t" + dict2.Value);
                }

        }

GridView中的dataTable结果: |---------------------|--------------|-------------| | Function | R&D | Dev | |---------------------|--------------|-------------| | Trainer | 3000 | | |---------------------|--------------|-------------| | Developer | 6000 | | |---------------------|--------------|-------------| | Consultant | 0 | | |---------------------|--------------|-------------| | Trainer | | 0 | |---------------------|--------------|-------------| | Developer | | 4000 | |---------------------|--------------|-------------| | Consultant | | 5000 | |---------------------|--------------|-------------|

首选结果:

|---------------------|--------------|-------------| | Function | R&D | Dev | |---------------------|--------------|-------------| | Trainer | 3000 | 0 | |---------------------|--------------|-------------| | Developer | 6000 | 4000 | |---------------------|--------------|-------------| | Consultant | 0 | 5000 | |---------------------|--------------|-------------| 我想用内部字典的不同键填充数据表的第一列,并根据它填充其他列,或者根据初始数据表创建所需的数据表。 任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net linq datatable


    【解决方案1】:

    我最近不得不在使用 2 个不同的 DataTables 时做这种事情,因为我自己不是专家我不能说这是最快的方法,但这应该适合你。

    string find = "Function = '" + dict2.Key + "'";
    DataRow[] foundRows = result.Select(find);
    if (foundRows.Length > 0)
    {
        DataRow row1 = foundRows[0];
        row1[dict.Key] = dict2.Value;
    }
    else
    {
        DataRow row2 = dt.NewRow();
        row2["Function"] = dict2.Key;
        row2[dict.Key] = dict2.Value;
        dt.Rows.Add(row2);
    }
    

    编辑:您应该将此代码放在最后一个 foreach 中。

    Results from testing

    【讨论】:

    • 谢谢你!像魅力一样工作。我知道必须在内部 foreach 中引用我的列,但不确定如何。我将在大型数据集上对其进行测试,看看效果如何。
    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多