【问题标题】:Varying amount of dictionaries in a DataTable数据表中不同数量的字典
【发布时间】:2010-12-22 09:25:28
【问题描述】:

之前我问了一个关于将已知数量的字典合并到 1 个数据表中的问题:Dictionaries in DataTable 达林为我手头的问题提供了令人满意的解决方案。 但是我的问题已经演变了。我不能再确定我得到了多少词典。事实上,它可以是 1 到 10 之间的任何数字。 因此,字典以集合的形式提供给我,即:

IList<IDictionary<string, string>>
静态字典数量的解决方案如下:

    var dic1 = new Dictionary() 
{ 
    { "A", "s" },
    { "B", "d" },
    { "C", "a" },
    { "D", "w" },
};

var dic2 = new Dictionary() 
{ 
    { "A", "z" },
    { "B", "e" },
    { "C", "r" },
    { "D", "t" },
};

var dic3 = new Dictionary() 
{ 
    { "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]);
}

现在,我怎样才能使这段代码适用于不同数量的字典(尤其是 Rows.Add(xxx) 部分,因为该行中的每一列本质上都是字典的值)

【问题讨论】:

    标签: c# list dictionary datatable collections


    【解决方案1】:

    我猜:

    foreach (var key in list[0].Keys) // assume the first defines everything
    {
        object[] rowData = new object[list.Count + 1];
        rowData[0] = key;
        for(int i = 0 ; i < list.Count ; i++) {
            rowData[i+1] = list[i][key];
        }
        table.Rows.Add(rowData);
    }
    

    顺便说一句,它可能(或者可能不)更容易使用params IDictionary&lt;string, string&gt;[](在这种情况下将.Count更改为.Length) - 但两者都应该工作。

    【讨论】:

    • 谢谢,我当然可以将此推断为我的现实世界问题!
    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多