C# ConcurrentDictionary:使用for循环遍历输出所有数据
在C#中,使用ConcurrentDictionary的for循环来输出每个数据可以按照以下步骤进行:
- 首先,创建一个ConcurrentDictionary对象并添加一些键值对。
ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
dictionary.TryAdd('key1', 1);
dictionary.TryAdd('key2', 2);
dictionary.TryAdd('key3', 3);
- 使用foreach循环遍历ConcurrentDictionary,并输出每个键值对。
foreach (var kvp in dictionary)
{
Console.WriteLine('Key: {0}, Value: {1}', kvp.Key, kvp.Value);
}
完整示例代码如下:
using System;
using System.Collections.Concurrent;
class Program
{
static void Main(string[] args)
{
ConcurrentDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>();
dictionary.TryAdd('key1', 1);
dictionary.TryAdd('key2', 2);
dictionary.TryAdd('key3', 3);
foreach (var kvp in dictionary)
{
Console.WriteLine('Key: {0}, Value: {1}', kvp.Key, kvp.Value);
}
}
}
运行上述代码,将会输出每个键值对的键和值。
原文地址: https://www.cveoy.top/t/topic/jsuq 著作权归作者所有。请勿转载和采集!