简体   繁体   English

字典 <string, int> 列出 <Dictionary<string, int> &gt;在C#中

[英]Dictionary<string, int> to List<Dictionary<string, int>> in c#

Is there a clean method to do this? 有没有一种干净的方法可以做到这一点?

I tried 我试过了

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

But that doesn't work, I'm looking for something similar to above if that is possible? 但这不起作用,如果可能的话,我正在寻找与上述类似的东西?

There are two statements in your question. 您的问题中有两个陈述。

Assuming first is correct then do 假设首先是正确的,然后做

myList.Add(myDict);

But if your second statement is correct then your first statement should be 但是,如果您的第二个陈述是正确的,那么您的第一个陈述应该是

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

Code: 码:

        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);

Something like this? 像这样吗

I think you need something like this: 我认为您需要这样的东西:

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();

And retrieve data in this way: 并以这种方式检索数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM