使用LINQ比较不同字典中具有相同键的项目

Ufu*_*arı 4 .net c# linq

我有两个带字符串键和不同值类型的字典.

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做到这一点?

Pra*_*ana 5

如果我找到你,

你可以内部加入这两个集合,然后再获取价值

var exp = form p in _properties
          join e in _expectations
          on p.key equals e.key
          select e;
Run Code Online (Sandbox Code Playgroud)

详细信息,您可以查看此图片: 在此输入图像描述


Tho*_*que 5

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)

(它避免了两次查找密钥)