【问题标题】:How do I output a Dictionary Value when iterating through something other than a KeyValuePair迭代 KeyValuePair 以外的内容时如何输出字典值
【发布时间】:2015-12-04 01:26:10
【问题描述】:

当值是列表时,我知道如何从字典中输出键和值,当我使用 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]

输出是有道理的,因为如果你有一个带有列表的字典,你必须作为 KeyValuePair 进行迭代才能得到实际的列表,但我是一个超级 C# 菜鸟,不确定如何在这种情况下正确获取列表。

感谢任何帮助。

【问题讨论】:

  • 这是第一个键的预期结果吗? "Key: A_list1, Value: 1,2,3"
  • 如果您对答案有任何疑问,请告诉我:)
  • 一旦我回到电脑前,我会执行你所说的,如果我有任何问题,我会提出问题。感谢您的快速回复!

标签: c# list dictionary


【解决方案1】:

您可以通过这种方式将List&lt;int&gt; 转换为字符串表示:

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;

【讨论】:

    【解决方案2】:

    默认情况下,当您将对象连接到字符串时,框架会为您在对象上执行对 ToString 的隐式调用。如您所见,基类objectToString 的默认实现只返回一个带有类型信息的字符串。如果您想要列表的任何替代字符串表示形式,您需要自己生成该字符串(例如:通过调用接收列表并返回字符串的方法)。

    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 就是您要查找的。​​p>

    【讨论】:

    • 感谢您的精彩解释。我希望我能接受这两个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多