我有两个带字符串键和不同值类型的字典.
private Dictionary<string, IProperty> _properties;
private Dictionary<string, Expectation> _expectations;
Run Code Online (Sandbox Code Playgroud)
我需要比较共享相同键的元素并获得匹配的期望.这是我在Expectation类中的方法签名.
public bool Matches(IProperty property)
Run Code Online (Sandbox Code Playgroud)
我怎么能用LINQ做到这一点?
如果我找到你,
你可以内部加入这两个集合,然后再获取价值
var exp = form p in _properties
join e in _expectations
on p.key equals e.key
select e;
Run Code Online (Sandbox Code Playgroud)
详细信息,您可以查看此图片:

var result = from pKey in _properties.Keys
where _expectations.ContainsKey(pKey)
let e = _expectations[pKey]
select e;
Run Code Online (Sandbox Code Playgroud)
它比连接更有效,因为它利用了键中的查找功能_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;
Run Code Online (Sandbox Code Playgroud)
(它避免了两次查找密钥)
| 归档时间: |
|
| 查看次数: |
3616 次 |
| 最近记录: |