c# - 使用 LINQ 比较具有相同键的不同词典中的项目

标签 c# .net linq

我有两个字典,它们有一个字符串键和不同的值类型。

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/

相关文章:

c# - 空文字参数类型重载解析

c# - 如何使用 LINQ-to-Wiki 从维基百科获取所有城市页面?

c# - LINQ 时间戳 - 自动更新时间戳列?

c# - 如何在 LINQ 中以更简洁的方式编写此示例?

c# - 如何使用 linq 从列表中删除尾随对象?

c# - 从流图像创建视频 C#

c# - Html.Action ("MyView", Model.SomeData) 作为 null 传入?

c# - 在C#中杀死TCP服务器的TCP客户端线程

c# - C# 中的动态相等

c# - 在 C# 中计算素数的最快方法?