我看到了一些不同的方法来迭代C#中的字典。有标准的方法吗?
当前回答
除了在使用
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
}
其他回答
如果您试图在C#中使用通用字典,就像在另一种语言中使用关联数组一样:
foreach(var item in myDictionary)
{
foo(item.Key);
bar(item.Value);
}
或者,如果只需要遍历密钥集合,请使用
foreach(var item in myDictionary.Keys)
{
foo(item);
}
最后,如果你只对价值观感兴趣:
foreach(var item in myDictionary.Values)
{
foo(item);
}
(请注意,var关键字是可选的C#3.0及以上版本的特性,您也可以在此处使用键/值的确切类型)
从C#7开始,您可以将对象分解为变量。我认为这是遍历字典的最佳方式。
例子:
在KeyValuePair<TKey,TVal>上创建一个扩展方法,对其进行解构:
public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)
{
key = pair.Key;
value = pair.Value;
}
按以下方式遍历任何字典<TKey,TVal>
// Dictionary can be of any types, just using 'int' and 'string' as examples.
Dictionary<int, string> dict = new Dictionary<int, string>();
// Deconstructor gets called here.
foreach (var (key, value) in dict)
{
Console.WriteLine($"{key} : {value}");
}
C#7.0引入了解构器,如果您正在使用.NET Core 2.0+应用程序,那么结构KeyValuePair<>已经为您提供了一个解构器()。因此,您可以做到:
var dic = new Dictionary<int, string>() { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (var (key, value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
//Or
foreach (var (_, value) in dic) {
Console.WriteLine($"Item [NO_ID] = {value}");
}
//Or
foreach ((int key, string value) in dic) {
Console.WriteLine($"Item [{key}] = {value}");
}
一般来说,在没有特定上下文的情况下要求“最佳方式”就像要求什么是最好的颜色?
一方面,有很多颜色,没有最好的颜色。这取决于需求,也常常取决于口味。
另一方面,有很多方法可以在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)
}
从这些示例中可以看到更多真实世界的用例。如果您不需要特定的订单,只需坚持“最直接的方式”(见上文)!
我将利用.NET 4.0+的优势,为最初接受的问题提供更新的答案:
foreach(var entry in MyDic)
{
// do something with entry.Value or entry.Key
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何合并字典的字典?
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Swift:声明一个空字典
- 将JSON字符串转换为HashMap
- 我如何循环通过一组记录在SQL Server?