检查一个列表是否包含其他列表中的任何元素

web*_*oob 10 c# linq

我只是尝试返回true,如果一个列表包含list2中的任何名称/值:

这将是我的结构:

public class TStockFilterAttributes
{
    public String Name { get; set; }
    public String Value { get; set; }
}

List<TStockFilterAttributes> List1 = new List<TStockFilterAttributes>();
List<TStockFilterAttributes> List2 = new List<TStockFilterAttributes>();
Run Code Online (Sandbox Code Playgroud)

这应该返回true:

List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
Run Code Online (Sandbox Code Playgroud)

但是这会返回false,因为Name && Value不匹配:

List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Foo" });
Run Code Online (Sandbox Code Playgroud)

每个列表可能包含许多不同的值,我只需要知道List1中的任何一个是否与List2中的任何一个匹配.

我尝试过使用:

return List1.Intersect(List2).Any();
Run Code Online (Sandbox Code Playgroud)

但是这似乎在所有情况下都返回false,我假设这是因为我在List中而不是简单的int/string中持有一个类?

Ser*_*kiy 8

覆盖EqualsGetHashCode实施您的课程:

public class TStockFilterAttributes
{
    public String Name { get; set; }
    public String Value { get; set; }

    public override bool Equals(object obj)
    {
        TStockFilterAttributes other = obj as TStockFilterAttributes;
        if (obj == null)
            return false;

        return Name == obj.Name && Value == obj.Value;
    }

    public override int GetHashCode()
    {
        return Name.GetHashCode() ^ Value.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

或提供比较器Intersect功能.


小智 6

假设性能无关紧要:

List1.Any(l1 => List2.Any(l2 => l1.Key == l2.Key && l1.Value == l2.Value));
Run Code Online (Sandbox Code Playgroud)

替代方案是覆盖Equals或使其成为Struct(可能不合适)