我有两个字典,它们有一个字符串键和不同的值类型。
private Dictionary<string, IProperty> _properties;
private Dictionary<string, Expectation> _expectations;
我需要比较共享相同键的元素并获得匹配的期望值。这是我在 Expectation 类中的方法签名。
public bool Matches(IProperty property)
我如何使用 LINQ 做到这一点?
最佳答案
var result = from pKey in _properties.Keys
where _expectations.ContainsKey(pKey)
let e = _expectations[pKey]
select e;
它比连接更有效,因为它利用了 _expectations
中的键查找。它可以通过使用这样的扩展方法稍微改进:
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TValue : class
{
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
return null;
}
var result = from pKey in _properties.Keys
let e = _expectations.GetValueOrDefault(pKey)
where e != null
select e;
(它避免了两次查找 key )
关于c# - 使用 LINQ 比较具有相同键的不同词典中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6994320/