tru*_*ype 3 c# dictionary list
我知道当值是List时如何从字典中输出键和值,当我使用a迭代字典时foreach(KeyValuePair<string,List<int>> test in myDictionary),但如果我必须使用不同类型的循环,如下例,我是不确定如何正确获取值.
我正在迭代列表,但使用字典,因为我按字母顺序排序.我知道还有其他方法可以做到这一点,这不是我的问题.
所以,我试图根据键按字母顺序输出键及其值.
string string1 = "A_list1";
List<int> list1 = new List<int> { 1, 2, 3 };
string string2 = "B_list2";
List<int> list2 = new List<int> { 4, 5, 7 };
string string3 = "C_list3";
List<int> list3 = new List<int> { 8, 9, 10 };
Dictionary<String, List<int>> myDictionary = new Dictionary<string, List<int>>();
myDictionary.Add(string2, list1);
myDictionary.Add(string1, list2);
myDictionary.Add(string3, list3);
var sortedAlphabeticallyMyDictionary = myDictionary.Keys.ToList();
sortedAlphabeticallyMyDictionary.Sort();
foreach (string myString in sortedAlphabeticallyMyDictionary)
{
MessageBox.Show("Key: " + myString + "\n" + "Value: " + myDictionary[myString] );
}
Run Code Online (Sandbox Code Playgroud)
产量
Key: A_list1
Value: System.Collections.Generic.List`1[System.Int32]
Key: B_list2
Value: System.Collections.Generic.List`1[System.Int32]
Key: C_list3
Value: System.Collections.Generic.List`1[System.Int32]
Run Code Online (Sandbox Code Playgroud)
输出是有意义的,因为如果你有一个包含List的Dictionary,你必须作为KeyValuePair迭代才能获得实际列表,但我是一个超级C#noob,并不确定如何获得在此实例中正确列出.
任何帮助表示赞赏.
您可以通过List<int>以下方式将a转换为字符串表示:
var list = new List<int> { 1, 2, 3 };
MessageBox.Show(string.Join(",", list.Select(x => x.ToString())));
Run Code Online (Sandbox Code Playgroud)
所以你可以使用这段代码:
foreach (string myString in sortedAlphabeticallyMyDictionary)
{
MessageBox.Show(string.Format("Key: {0} \n Value: {1}" , myString,
string.Join(",", myDictionary[myString].Select(x => x.ToString()))) );
}
Run Code Online (Sandbox Code Playgroud)
别忘了添加 using System.Linq;
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |