如果我有一个字典列表
IEnumerable<IDictionary<string, float>> enumeration
Run Code Online (Sandbox Code Playgroud)
我可以对它执行Linq查询,以便我可以使用相同的键从枚举中的每个字典中选择一个值吗?
我可以循环执行此操作:
float f;
foreach (var dictionary in enumeration)
{
if (dictionary.TryGetValue("some key", out f))
{
Console.WriteLine(f);
}
}
Run Code Online (Sandbox Code Playgroud)
(最终的计划是将查询的性能与等效的嵌套循环语句进行比较(枚举本身由另一个查询或一组等效的循环组成).)
你在寻找这样的东西:
IEnumerable<float> vals = enumeration.Where( d => d.ContainsKey( "some key" ) )
.Select( d => d["some key"] );
Run Code Online (Sandbox Code Playgroud)
此查询首先识别序列中的哪些字典包含指定的键,然后为每个字典检索给定键的值.
这不如使用循环那样有效TryGetValue(),因为它将执行两个字典访问 - 一个用于Where另一个用于Select.或者,您可以创建一个安全方法,从字典中返回值或默认值,然后筛选出默认值.这消除了重复的字典查找.
public static class DictionaryExt {
public static TValue FindOrDefault<TKey,TValue>(
this Dictionary<TKey,TValue> dic,
TKey key, TValue defaultValue )
{
TValue val;
return dic.TryGetValue( key, out val ) ? val : defaultValue;
}
}
enumeration.Select( d => d.FindOrDefault( "some key", float.NaN ) )
.Where ( f => f != float.NaN );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
755 次 |
| 最近记录: |