在 C# 中,如何输出 Dictionary 类的内容?
一旦你加载了一个带有键和值的 Dictionary 类,我如何循环它们并在 foreach 循环中输出各个值?
在 C# 中,如何输出 Dictionary 类的内容?
一旦你加载了一个带有键和值的 Dictionary 类,我如何循环它们并在 foreach 循环中输出各个值?
这是来自http://www.dotnetperls.com/dictionary的示例
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Example Dictionary again
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
// Loop over pairs with foreach
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
// Use var keyword to enumerate dictionary
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
}
}
最后一个循环使用var来声明 KeyValuePair 对象。这种方式更容易,因为您不必担心声明字典中使用的类型,并为 CLR 生成相同的结果。
foreach (KeyValuePair<string, int> pair in myDictionary)
{
Console.WriteLine("{0}, {1}",
pair.Key,
pair.Value);
}
尝试这个
Dictionary<object, object> dummyDictionary = new Dictionary<object, object>
{
{"India","Delhi"},
{"USA","WashingtonDC"},
{"Bangaladesh","Dhaka"},
{"Pakistan","Karachi"}
};
//foreach循环构造
foreach (KeyValuePair<object, object> kvp in dummyDictionary)
{
Console.WriteLine(string.Format("Key = {0} Value = {1}", kvp.Key, kvp.Value));
}
//使用 Linq 和 Foreach 扩展方法
var result =
(from kvp in dummyDictionary
select new
{
Key = kvp.Key
,
Value = kvp.Value
});
result.ToList().ForEach(kvp => Console.WriteLine(string.Format("Key = {0} Value = {1}", kvp.Key, kvp.Value)));
Console.ReadKey();
foreach(var key in pair.Keys){
Console.WriteLine("{0} - {1}", key, pair[key]);
}
你是什么意思,说出并输出个人价值观?您是否希望只看到独特的价值?
Dictionary<string, string> dict = new Dictionary<string, string>
{
{"1","one"},
{"2","two"},
{"3","three"},
{"4","one"}
};
foreach (var value in dict.Values.Distinct())
{
Console.WriteLine(value);
}
Console.ReadLine();
也就是说,您可以使用Distinct()
来获取唯一值,而 dict.Values
字典ValueColection
的