我有很多代码块,比如
foreach ( KeyValuePair<string, int> thisFriend in this.names )
{
Console.WriteLine("{0} ({1})", thisFriend.Key, thisFriend.Value);
}
其中this.names
是Dictionary<string,int>
,我想知道是否有办法让这个更紧凑而不会失去任何效率(通过中间转换或诸如此类)。我可以做点什么吗
this.Names.ForEach(f => Console.WriteLine("{0} ({1})", f.Key, f.Value));
???
答案 0 :(得分:3)
您可以编写自定义扩展方法:
public static class DictionaryExtensions
{
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Action<TKey, TValue> action)
{
foreach (var pair in dictionary)
{
action(pair.Key, pair.Value);
}
}
}
// ...
d.ForEach((s, s1) =>
{
Console.WriteLine($"{s} ({s1})");
});
甚至是使用IEnumerable
的更通用的。
但是,在我看来,它并没有带来任何改进。有3行代码,没有办法做到这一点。使用foreach
方便易读。您可以直接停止明确定义类型。请改用var
- 它不会降低可读性,但可以节省大量时间:
foreach ( var thisFriend in this.names )
{
Console.WriteLine($"{thisFriend.Key} ({thisFriend.Value})");
}
答案 1 :(得分:0)
您可以枚举核心集合(但您必须先将KeysCollecton
转换为列表)
this.Names.Keys.ToList().ForEach(k => Console.WriteLine("{0}:{1}", k, this.Names[k]));
这肯定更简洁,但不确定这是否是您正在寻找的。 p>