加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在迭代KeyValuePair以外的其他内容时输出字典值

发布时间:2020-12-15 23:29:04 所属栏目:百科 来源:网络整理
导读:当我使用foreach(KeyValuePair string,List int test in myDictionary)迭代字典时,我知道如何在值为List时从字典输出键和值,但是如果我有使用不同类型的循环,如下例所示,我不确定如何正确获取值. 我正在迭代列表,但使用字典,因为我按字母顺序排序.我知道还有
当我使用foreach(KeyValuePair< string,List< int>> test in myDictionary)迭代字典时,我知道如何在值为List时从字典输出键和值,但是如果我有使用不同类型的循环,如下例所示,我不确定如何正确获取值.

我正在迭代列表,但使用字典,因为我按字母顺序排序.我知道还有其他方法可以做到这一点,这不是我的问题.

所以,我试图根据键按字母顺序输出键及其值.

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< int>以这种方式表示字符串:

var list = new List<int> { 1,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()))) );
}

不要忘记使用System.Linq添加;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读