我只是想在一个列表中检查是否包含list2中的任何Name/Value,如果存在则返回true:
这将是我的结构:
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>();
这应该返回true:
List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
但是这会返回false,因为名称和值不匹配:
List1.Add(new TStockFilterAttributes { Name = "Foo", Value = "Bar" });
List2.Add(new TStockFilterAttributes { Name = "Foo", Value = "Foo" });
每个列表都可能包含许多不同的值,我只需要知道List1中的任何一个是否与List2中的任何一个匹配。
我尝试过使用:
return List1.Intersect(List2).Any();
但是在所有情况下似乎都返回false,我猜这是因为我在List中持有一个类而不是一个简单的int/string?
Intersect
操作基于引用进行比较。因为每次都会创建一个新的对象,所以你需要编写自己的IEqualityComparer<TStockFilterAttributes>
。 - Patryk Ćwiek