迭代KeyValuePair以外的内容时,如何输出Dictionary Value
本文关键字:何输出 输出 Value Dictionary KeyValuePair 迭代 | 更新日期: 2023-09-27 18:25:32
当值是List时,当我使用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] );
}
输出
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]
输出是有意义的,因为如果你有一个包含List的Dictionary,你必须作为KeyValuePair进行迭代才能得到实际的列表,但我是一个超级C#noob,不知道如何在这个例子中正确地得到List。
感谢您的帮助。
您可以通过以下方式将List<int>
转换为字符串表示:
var list = new List<int> { 1, 2, 3 };
MessageBox.Show(string.Join(",", list.Select(x => x.ToString())));
所以你可以使用这个代码:
foreach (string myString in sortedAlphabeticallyMyDictionary)
{
MessageBox.Show(string.Format("Key: {0} 'n Value: {1}" , myString,
string.Join(",", myDictionary[myString].Select(x => x.ToString()))) );
}
不要忘记添加using System.Linq;
默认情况下,当您将对象连接到字符串时,框架会为您对对象执行对ToString
的隐式调用。基类object
中ToString
的默认实现只返回一个包含类型信息的字符串,正如您所发现的那样。如果您想要列表的任何类型的替代字符串表示,您需要自己生成该字符串(例如:通过调用接收列表并返回字符串的方法)。
MessageBox.Show("Key: " + myString + "'n" + "Value: " + GetListAsString(myDictionary[myString]));
然后:
private static string GetListAsString(List<int> list) {
StringBuilder builder = new StringBuilder();
string commaSep = ", ";
string sep = "";
foreach (int val in list) {
builder.Append(sep);
builder.Append(val);
sep = commaSep;
}
return builder.ToString();
}
顺便说一句,如果你想要一组排序的键,每个键都有一个相关的值,那么你要找的就是SortedDictionary。