【问题标题】:Dictionaries in DataTable数据表中的字典
【发布时间】:2009-12-02 07:29:52
【问题描述】:

假设我有 3 个 Dictionary<string, string> 对象。所有 3 个都有相同的密钥,如下所示:

Dic1 Dic2 Dic3 K V K V K V 阿斯阿兹阿我 B d B e B u 卡卡罗 D w D t D p

现在,我想将这些字典合并到一个 DataTable 中,DataTable 应如下所示:

阿斯齐 德优 卡罗尔 D w t p

关于如何从单独的字典到 DataTable 中的组合字典的任何指针或想法?

【问题讨论】:

    标签: c# dictionary datatable


    【解决方案1】:
    var dic1 = new Dictionary<string, string>() 
    { 
        { "A", "s" },
        { "B", "d" },
        { "C", "a" },
        { "D", "w" },
    };
    
    var dic2 = new Dictionary<string, string>() 
    { 
        { "A", "z" },
        { "B", "e" },
        { "C", "r" },
        { "D", "t" },
    };
    
    var dic3 = new Dictionary<string, string>() 
    { 
        { "A", "i" },
        { "B", "o" },
        { "C", "u" },
        { "D", "p" },
    };
    
    var table = new DataTable();
    table.Columns.Add("K", typeof(string));
    table.Columns.Add("c1", typeof(string));
    table.Columns.Add("c2", typeof(string));
    table.Columns.Add("c3", typeof(string));
    foreach (var key in dic1.Keys)
    {
        table.Rows.Add(key, dic1[key], dic2[key], dic3[key]);
    }
    

    【讨论】:

    • 当然,我怎么会错过这个:/ 我真的需要更多地提高我的可视化技能!谢谢:-)
    【解决方案2】:

    假设 DataTable 已实例化并添加了列。

    foreach (string k in Dic1.Keys)
    {
        DataRow row = table.NewRow();
        row[0] = k;
        row[1] = Dic1[k];
        if (Dic2.ContainsKey(k))
            row[2] = Dic2[k];
        if (Dic3.ContainsKey(k))
            row[3] = Dic3[k];
    
        table.Rows.Add(row);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 2022-12-05
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多