我看到了一些不同的方法来迭代C#中的字典。有标准的方法吗?
当前回答
使用C#7,将此扩展方法添加到解决方案的任何项目中:
public static class IDictionaryExtensions
{
public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
this IDictionary<TKey, TValue> dict)
{
foreach (KeyValuePair<TKey, TValue> kvp in dict)
yield return (kvp.Key, kvp.Value);
}
}
使用这个简单的语法
foreach (var(id, value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
或者这个,如果你喜欢的话
foreach ((string id, object value) in dict.Tuples())
{
// your code using 'id' and 'value'
}
代替传统的
foreach (KeyValuePair<string, object> kvp in dict)
{
string id = kvp.Key;
object value = kvp.Value;
// your code using 'id' and 'value'
}
扩展方法将IDictionary<TKey,TValue>的KeyValuePair转换为强类型元组,允许您使用这种新的舒适语法。
它只将所需的字典条目转换为元组,因此不会将整个字典转换为元组。因此,不存在与此相关的性能问题。
与直接使用KeyValuePair相比,调用扩展方法来创建元组的成本很低,如果您要将KeyValuePail的财产Key和Value分配给新的循环变量,那么这应该不是问题。
实际上,这种新语法非常适合大多数情况,除了低级别的超高性能场景,在这种情况下,您仍然可以选择不在特定位置使用它。
看看这个:MSDN博客-C#7中的新功能
其他回答
最好的答案当然是:想一想,如果你计划迭代,你是否可以使用比字典更合适的数据结构-正如Vikas Gupta在问题讨论开始时已经提到的那样。但作为整个主题的讨论仍然缺乏令人惊讶的好选择。一个是:
SortedList<string, string> x = new SortedList<string, string>();
x.Add("key1", "value1");
x.Add("key2", "value2");
x["key3"] = "value3";
foreach( KeyValuePair<string, string> kvPair in x )
Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");
为什么它会被认为是在字典上迭代的代码味道(例如,通过foreach(KeyValuePair<,>)?
清洁编码的基本原则:“表达意图!”罗伯特·C·马丁在《干净的代码》中写道:“选择能揭示意图的名字”。很明显,单是命名太弱了。“表达(揭示)每一个编码决策的意图”更好地表达了这一点。
一个相关的原则是“最小惊讶原则”。
为什么这与遍历字典有关?选择字典表达了选择数据结构的意图,该数据结构主要用于按关键字查找数据。如今,.NET中有太多的替代方案,如果您想遍历键/值对,可以选择其他选项。
此外:如果您迭代某个项目,您必须揭示项目的排序方式和预期排序方式!尽管Dictionary的已知实现按照添加项的顺序对密钥集合进行排序-AFAIK,Dictionary没有关于订购的可靠规范(有吗?)。
但替代方案是什么?
TLDR:SortedList:如果您的集合没有变得太大,一个简单的解决方案是使用SortedList<,>,它还为键/值对提供了完整的索引。
微软有一篇关于提及和解释试衣系列的长文:键控集合
提到最重要的:KeyedCollection<,>和SortedDictionary<,>。SortedDictionary<,>比SortedList快一点,仅当它变大时才插入,但缺少索引,并且仅当插入的O(log n)优先于其他操作时才需要。如果您真的需要O(1)来插入并接受较慢的迭代,则必须使用简单的Dictionary<,>。显然,对于每种可能的操作,没有最快的数据结构。。
此外,还有ImmutableSortedDictionary<,>。
如果一个数据结构不是您所需要的,那么从Dictionary<,>或甚至从新的ConcurrentDictionary>派生,并添加显式迭代/排序函数!
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
取决于你是在寻找关键点还是值。。。
来自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);
}
除了在使用
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
or
foreach(var entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
最完整的是以下内容,因为您可以从初始化中看到字典类型,kvp是KeyValuePair
var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x
foreach(var kvp in myDictionary)//iterate over dictionary
{
// do something with kvp.Value or kvp.Key
}
我想说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进行异常处理是最佳实践
- 替换字符串中第一次出现的模式