我看到了一些不同的方法来迭代C#中的字典。有标准的方法吗?
当前回答
迭代字典的最简单形式:
foreach(var item in myDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
其他回答
根据MSDN上的官方文档,迭代字典的标准方法是:
foreach (DictionaryEntry entry in myDictionary)
{
//Read entry.Key and entry.Value here
}
您也可以在用于多线程处理的大型字典上尝试此操作。
dictionary
.AsParallel()
.ForAll(pair =>
{
// Process pair.Key and pair.Value here
});
使用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中的新功能
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
字典<TKey, TValue>它是c#中的一个泛型集合类,它以键值格式存储数据。键值必须是唯一的,不能为null,而值可以是重复的和null。由于字典中的每个项都被视为KeyValuePair<TKey, TValue>表示键及其值的结构。因此我们应该采用元素类型KeyValuePair<TKey, 元素迭代期间的TValue>。下面是示例。
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"One");
dict.Add(2,"Two");
dict.Add(3,"Three");
foreach (KeyValuePair<int, string> item in dict)
{
Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}
推荐文章
- 在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进行异常处理是最佳实践
- 替换字符串中第一次出现的模式