C#LINQ比较列表值

Dar*_*ung 3 c# linq

我有两个不同自定义类型的列表.两种类型共享2个共同属性.

例如:

List<foo>;
List<bar>;
Run Code Online (Sandbox Code Playgroud)

它们都具有属性,例如名为Name和Age.

我想返回一个包含所有bar对象的新List,其中bar的Name和Age属性出现在任何foo对象中.最好的方法是什么?

谢谢

Jon*_*eet 11

假设共享属性正确实现了相等,您可能希望执行以下操作:

// In an extensions class somewhere. This should really be in the standard lib.
// We need it for the sake of type inference.
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
    return new HashSet<T>(items);
}

var shared = foos.Select(foo => new { foo.SharedProperty1, foo.SharedProperty2 })
                 .ToHashSet();

var query = bars.Where(bar => shared.Contains(new { bar.SharedProperty1,
                                                    bar.SharedProperty2 }));
Run Code Online (Sandbox Code Playgroud)

使用连接的其他选项肯定会起作用 - 但我发现这更清楚,表达了你只想查看每个bar条目一次,即使有几个foo具有该属性的项目.