C# Linq check if a list contains all of another lists items when comparing on one property

user8981612 picture user8981612 · Nov 21, 2017 · Viewed 19.1k times · Source

I am learning Linq and I have two object lists. I want to compare one of these lists against the other to see if all of one of the properties of the objects within it can be matched to those in the other list. So, I provide code for that but I want to change it to Linq expressions.

        var list1 = new List<Product>
        {
            new Product{SupplierId = 1,ProductName = "Name1"},
            new Product{SupplierId = 2,ProductName = "Name2"},
            new Product{SupplierId = 3,ProductName = "Name3"},
            new Product{SupplierId = 4,ProductName = "Name4"}
        };
        var list2 = new List<Product>
        {
            new Product {SupplierId = 1,ProductName = "Name5"},
            new Product {SupplierId = 4,ProductName = "Name6"}
        };

    private static bool CheckLists(List<Product> list1, List<Product> list2)
    {
        foreach (var product2 in list2)
        {
            bool result = false;
            foreach (var product in list1)
            {
                if (product.SupplierId == product2.SupplierId)
                {
                    result = true;
                    break;
                }
            }
            if (!result)
            {
                return false;
            }
        }
        return true;
    }

How can i do it using Linq ?

Answer

Steve picture Steve · Nov 21, 2017
bool existsCheck = list1.All(x => list2.Any(y => x.SupplierId == y.SupplierId));

would tell you if all of list1's items are in list2.