Linq to check if item in one list is in another list RRS feed

  • Question

  • I know in conventional code it would be a foreach loop within another foreach loop.  Is there a good example of this or is this something better accomplished with the conventional code method?



    Wednesday, June 5, 2019 12:37 PM

All replies

  • Hello,

    Look at using Any

    public void MyTestMethod()
        var firstList = new List<string>() {"Mazda","Ford","Chevy","Alpha"};
        var secondList = new List<string>() { "Volkswagen", "Ford", "BMW", "Daimler" };
        var result = secondList.Any(car => car == "Ford");

    The above Assert returns true since Ford is in the first list.

    Example using a list for a class 

    public class Company
        public int Id { get; set; }
        public string Name { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Title { get; set; }
        public override string ToString()
            return $"{Id}, '{Name}'";

    public void MyTestMethod()
        var customer1 = new Company() {FirstName = "Karen", LastName = "Payne"};
        var customer2 = new Company() {FirstName = "Mary", LastName = "Jackson"};
        var customer3 = new Company() {FirstName = "Bill", LastName = "Adams"};
        var cust1 = new List<Company>() {customer1,customer2,customer3};
        var cust2 = new List<Company>() {customer1,customer2};
        Assert.IsTrue(cust2.Any(cust => cust.FirstName == "Karen" && cust.LastName == "Payne"));
        Assert.IsFalse(cust2.Any(cust => cust.FirstName == "Karen" && cust.LastName == "Payne"));

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Wednesday, June 5, 2019 1:21 PM
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Monday, June 10, 2019 8:28 AM