我有 2 个列表,其中包含一些数据:
List1.Add(new Filter { Name = "Foo", Value = "Bar" });
List2.Add(new Filter { Name = "Foo", Value = "Bar" });
如果 List1 包含 List2 中的所有值,我想使用 Linq 返回 true,上面的示例显然会返回 true 但这是一个示例,但如果我添加了
List2.Add(new Filter { Name = "Foo1", Value = "Bar1" });
那么它应该返回 false。
我开始沿着这条线走下去:
var Result = from item1 in List1
join item2 in List2 on item1.Name equals item2.Name
new { item1, item2 };
但这只会匹配名称,我很确定我走错了路。
编辑:澄清一下,我不只想要 VALUE 属性。两个列表中的名称和值必须匹配。
请您参考如下方法:
您可以使用 Except :
var l1Vals = List1.Select(f => f.Value);
var l2Vals = List2.Select(f => f.Value);
var notInL1 = l2Vals.Except(l1Vals);
if(notInL1.Any())
{
// no, not all Values of List2 are in List1
}
编辑 根据您上次编辑,您想要比较 Filter 的所有属性, 最好的方法是创建自定义 IEqualityComparer<Filter> 并将其用作此 Enumerable.Except overload 的参数:
public class Filter {
public String Name { get; set; }
public String Value { get; set; }
public class Comparer : IEqualityComparer<Filter>
{
public bool Equals(Filter x, Filter y)
{
if(ReferenceEquals(x, y))
return true;
else if(x==null || y==null)
return false;
return x.Name == y.Name
&& x.Value == y.Value;
}
public int GetHashCode(Filter obj)
{
unchecked
{
int hash = 17;
hash = hash * 23 + obj.Name.GetHashCode();
hash = hash * 23 + obj.Value.GetHashCode();
return hash;
}
}
}
}
现在可以了:
var notInL1 = List2.Except(List1, new Filter.Comparer());
if (notInL1.Any())
{
// no, not all properties of all objects in List2 are same in List1
// notInL1 contains the set difference
}
