我看到了一些不同的方法来迭代C#中的字典。有标准的方法吗?
当前回答
取决于你是在寻找关键点还是值。。。
来自MSDN Dictionary(TKey,TValue)类描述:
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
Console.WriteLine("Key = {0}", s);
}
其他回答
一般来说,在没有特定上下文的情况下要求“最佳方式”就像要求什么是最好的颜色?
一方面,有很多颜色,没有最好的颜色。这取决于需求,也常常取决于口味。
另一方面,有很多方法可以在C#中迭代字典,没有最好的方法。这取决于需求,也常常取决于口味。
最直接的方式
foreach (var kvp in items)
{
// key is kvp.Key
doStuff(kvp.Value)
}
如果您只需要值(允许将其称为item,比kvp.value更可读)。
foreach (var item in items.Values)
{
doStuff(item)
}
如果您需要特定的排序顺序
一般来说,初学者对词典的列举顺序感到惊讶。
LINQ提供了一种简洁的语法,允许指定顺序(以及许多其他事情),例如:
foreach (var kvp in items.OrderBy(kvp => kvp.Key))
{
// key is kvp.Key
doStuff(kvp.Value)
}
同样,您可能只需要值。LINQ还提供了一个简洁的解决方案:
直接迭代值(允许将其称为item,比kvp.value更可读)但按按键排序
这里是:
foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
doStuff(item)
}
从这些示例中可以看到更多真实世界的用例。如果您不需要特定的订单,只需坚持“最直接的方式”(见上文)!
迭代字典的最简单形式:
foreach(var item in myDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
我只想加上我的2美分,因为大多数答案都与foreach循环有关。请查看以下代码:
Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();
//Add some entries to the dictionary
myProductPrices.ToList().ForEach(kvP =>
{
kvP.Value *= 1.15;
Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));
});
尽管这增加了一个额外的“.ToList()”调用,但性能可能会略有改善(正如这里指出的foreach vs someList.foreach(){}),尤其是在处理大型词典和并行运行时,没有选择/根本不会产生效果。
此外,请注意,您无法在foreach循环中为“Value”属性赋值。另一方面,您也可以操作“Key”,可能会在运行时遇到麻烦。
当您只想“读取”键和值时,也可以使用IEnumerable.Select()。
var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );
foreach是最快的,如果只迭代___个值,它也会更快
我想说foreach是标准的方法,尽管这显然取决于你想要什么
foreach(var kvp in my_dictionary) {
...
}
这就是你要找的吗?
推荐文章
- 在Bash中模拟do-while循环
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 加快R中的循环操作
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- 在STL地图中,使用map::insert比[]更好吗?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式