检查list1内容是否与list2内容匹配

时间:2012-11-20 09:57:29

标签: c# linq

我有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属性。名称&&两个列表中的值必须匹配。

3 个答案:

答案 0 :(得分:4)

您可以使用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
}

答案 1 :(得分:0)

你可以尝试:

bool areAllElementsInList2 = list1.All(i => list2.Contains(i));

Contains-Methode使用Equals-Methode指定项目在该列表中是否存在。所以你应该覆盖Filter-Class的Equals-Methode。

或者你试试:

bool areAllElementsInList2 = list1.All(i1 => list2.Any(i2 => i1.Name == i2.Name && i1.Value == i2.Value));

HTH Tobi

答案 2 :(得分:0)

bool list1doesNotContainAllFromList2 = list2.Except(list1).Any();

请注意,如果您需要使用集合 - 比较等,最好使用HashSet<>集合而不是List<> - 它有ExceptWith或{{1}等方法这将比标准LINQ运算符执行得更快。

相关问题