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

问题描述:

我正在尝试创建一个Dictionary<string,int>项目的列表。我不知道如何在列表中添加项目以及如何在遍历列表时返回值。我想在C#中使用它,如下所示:如何在.NET中创建词典列表?

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

在哪种语言? – 2011-04-14 09:27:25

+1

代码示例和语言标签请 – 2011-04-14 09:27:27

+0

我想在C#中使用它。 like public list > MyList =新的列表>(); – Vivek 2011-04-14 09:31:59

我想这就是你要找的东西?

{ 
    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)); 
} 
+0

是接近你答案的东西。谢谢你的回复。 – Vivek 2011-04-14 09:41:39

+0

谢谢大家的回复。 – Vivek 2011-04-14 09:44:20

+7

如果你感到快乐,你应该接受某人的回答。欢迎来到SO! – Jaapjan 2011-04-14 09:52:50

我认为你必须知道在哪个官吏中你必须添加新的价值。所以列表是问题。你不能识别里面的字典。

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

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; 

    } 

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

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

Enjoy!

+1

从来没有听说过这个!惊人!非常感谢 :) – IfElseTryCatch 2017-05-19 08:07:53