下面是"C#中Dictionary泛型集合7种常见的用法"的完整攻略:
1. 创建Dictionary对象
使用Dictionary之前,首先需要创建Dictionary对象。可以通过以下代码创建:
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
其中,TKey是键的类型,TValue是值的类型。
2. 添加键值对
向Dictionary中添加键值对可以使用Add方法:
dict.Add(key, value);
也可以使用索引器:
dict[key] = value;
3. 访问值
通过Dictionary中的键可以访问到相应的值:
TValue value = dict[key];
需要注意的是,如果键不存在,访问将会抛出异常。此时可以使用TryGetValue方法:
bool success = dict.TryGetValue(key, out TValue value);
4. 遍历Dictionary
可以通过foreach循环遍历Dictionary中的所有键值对,如下所示:
foreach (KeyValuePair<TKey, TValue> kvp in dict)
{
TKey key = kvp.Key;
TValue value = kvp.Value;
}
也可以遍历所有的键或值:
foreach (TKey key in dict.Keys)
{
// do something with key
}
foreach (TValue value in dict.Values)
{
// do something with value
}
5. 字典初始化器
可以使用C# 6.0中的字典初始化器简化添加操作:
Dictionary<string, int> dict = new Dictionary<string, int>()
{
["one"] = 1,
["two"] = 2,
["three"] = 3
};
6. LINQ查询
可以使用LINQ查询想要的键值对或者对键值对的值进行过滤、排序等操作,如下所示:
var query = from kvp in dict
where kvp.Value > 10
orderby kvp.Key
select kvp;
foreach (KeyValuePair<TKey, TValue> kvp in query)
{
TKey key = kvp.Key;
TValue value = kvp.Value;
}
7. 转换为List
最后,可以将Dictionary转换为List进行多种操作:
List<KeyValuePair<TKey, TValue>> list = dict.ToList();
以上就是“C#中Dictionary泛型集合7种常见的用法”的完整攻略了。
下面给出两条示例说明:
示例1 前30个斐波那契数列
Dictionary <int,int> dict = new Dictionary<int,int>()
{
[0] = 0,
[1] = 1
};
for (int i = 2; i < 30; i++)
{
int value = dict[i - 1] + dict[i - 2];
dict[i] = value;
}
foreach (KeyValuePair<int, int> kvp in dict)
{
Console.WriteLine("key:{0}, value:{1}", kvp.Key, kvp.Value);
}
输出结果:
key:0, value:0
key:1, value:1
key:2, value:1
key:3, value:2
key:4, value:3
key:5, value:5
key:6, value:8
key:7, value:13
key:8, value:21
key:9, value:34
key:10, value:55
key:11, value:89
key:12, value:144
key:13, value:233
key:14, value:377
key:15, value:610
key:16, value:987
key:17, value:1597
key:18, value:2584
key:19, value:4181
key:20, value:6765
key:21, value:10946
key:22, value:17711
key:23, value:28657
key:24, value:46368
key:25, value:75025
key:26, value:121393
key:27, value:196418
key:28, value:317811
key:29, value:514229
示例2 统计数组中每个元素的数量
int[] arr = { 1, 2, 3, 3, 4, 4, 4, 5 };
Dictionary<int, int> dict = new Dictionary<int, int>();
foreach (int i in arr)
{
if (!dict.ContainsKey(i))
{
dict.Add(i, 1);
}
else
{
dict[i]++;
}
}
foreach (KeyValuePair<int, int> kvp in dict)
{
Console.WriteLine("key:{0}, count:{1}", kvp.Key, kvp.Value);
}
输出结果:
key:1, count:1
key:2, count:1
key:3, count:2
key:4, count:3
key:5, count:1
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#中Dictionary泛型集合7种常见的用法 - Python技术站