如何在.net中创建一个字典列表

本文关键字:一个 字典 列表 net 创建 | 更新日期: 2023-09-27 17:50:14

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

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

如何在.net中创建一个字典列表

我想这就是你要找的?

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

我认为您必须知道您必须在哪些字典中添加新值。所以《名单》就是问题所在。你认不出里面的字典。

我的解决方案是一个字典集合类。它可以像这样:

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