繁体   English   中英

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

[英]Dictionary<string, 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;

暂无
暂无

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

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