字典<字符串, int> to List<Dictionary<string, int>> in c#



有没有干净的方法来做到这一点?

我试过了

List<Dictionary<string, int>> myList = new List<Dictionary<string, int>>();
myList = myDict.ToList();

但这行不通,如果可能的话,我正在寻找类似于上面的东西?

你的问题中有两个陈述。

假设第一个是正确的,然后做

myList.Add(myDict);

但是如果你的第二个陈述是正确的,那么你的第一个陈述应该是

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

代码:

        Dictionary<string, int> myDict = new Dictionary<string, int>();
        myDict.Add("1", 1);
        myDict.Add("2", 2);
        myDict.Add("3", 3);
        myDict.Add("4", 4);
        myDict.Add("5", 5);
        List<Dictionary<string, int>> myList = new List<Dictionary<string, int>>();
        myList.Add(myDict);

像这样的东西?

我认为你需要这样的东西:

Dictionary<int, string> myDict = new Dictionary<int, string>();
myDict.Add(1, "one");
myDict.Add(2, "two");
myDict.Add(3, "three");
List<KeyValuePair<int, string>> myList = myDict.ToList();

并以这种方式检索数据:

// example get key and value
var myKey = myList[0].Key;
var myVal = myList[0].Value;

最新更新