如何在.NET中创建字典列表?

时间:2011-04-14 09:23:46

标签: c# .net list dictionary

我正在尝试创建一个Dictionary<string,int>项列表。我不确定如何在列表中添加项目以及如何在遍历列表时返回值。我想在C#中使用它,就像这样:

public List<Dictionary<string,int>> MyList= new List<Dictionary<string,int>>();

4 个答案:

答案 0 :(得分:22)

我认为这就是你要找的东西?

{
    MyList.Add(new Dictionary<string,int>());
    MyList.Add(new Dictionary<string,int>());
    MyList[0].Add("Dictionary 1", 1);
    MyList[0].Add("Dictionary 1", 2);
    MyList[0].Add("Dictionary 2", 3);
    MyList[0].Add("Dictionary 2", 4);
    foreach (var dictionary in MyList)
        foreach (var keyValue in dictionary)
            Console.WriteLine(string.Format("{0} {1}", keyValue.Key, keyValue.Value));
}

答案 1 :(得分:18)

5年后发生了很多变化......您现在可以执行以下操作:

ListDictionary list = new ListDictionary();
list.Add("Hello", "Test1");
list.Add("Hello", "Test2");
list.Add("Hello", "Test3");

享受!

答案 2 :(得分:4)

我认为你必须知道你必须在哪些dictinaries中添加你的新价值。所以列表就是问题所在。你无法在里面识别字典。

我的解决方案是字典集合类。 它看起来像这样:

  public class DictionaryCollection<TType> : Dictionary<string,Dictionary<string,TType>> {
    public void Add(string dictionaryKey,string key, TType value) {

        if(!ContainsKey(dictionaryKey))
            Add(dictionaryKey,new Dictionary<string, TType>());

        this[dictionaryKey].Add(key,value);
    }

    public TType Get(string dictionaryKey,string key) {
        return this[dictionaryKey][key];
    }
}

然后你可以像这样使用它:

var dictionaryCollection = new DictionaryCollection<int>
                                       {
                                           {"dic1", "Key1", 1},
                                           {"dic1", "Key2", 2},
                                           {"dic1", "Key3", 3},
                                           {"dic2", "Key1", 1}
                                       };

答案 3 :(得分:1)

   // Try KeyValuePair Please.. Worked for me


    private List<KeyValuePair<string, int>> return_list_of_dictionary()
    {

        List<KeyValuePair<string, int>> _list = new List<KeyValuePair<string, int>>();

        Dictionary<string, int> _dictonary = new Dictionary<string, int>()
        {
            {"Key1",1},
            {"Key2",2},
            {"Key3",3},
        };



        foreach (KeyValuePair<string, int> i in _dictonary)
        {
            _list.Add(i);
        }

        return _list;

    }