[c#] How to check list A contains any value from list B?

List A:

1, 2, 3, 4

List B:

2, 5

How to check if list A contains any value from list B?

e.g. something like A.contains(a=>a.id = B.id)?

This question is related to c# linq list

The answer is


I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

I use this to count:

int cnt = 0;

foreach (var lA in listA)
{
    if (listB.Contains(lA))
    {
        cnt++;
    }
}

You can check if a list is inside of another list with this

var list1 = new List<int> { 1, 2, 3, 4, 6 };
var list2 = new List<int> { 2, 3 };
bool a = list1.Any(c => list2.Contains(c));

For faster and short solution you can use HashSet instead of List.

a.Overlaps(b);

Overlaps documentation

This method is an O(n) instead of O(n^2) with two lists.


Sorry, if this is irelevant, but will return list with matches using FindAll() in case you need this:

        private bool IsContain(string cont)
    {
        List<string> ListToMatch= new List<string>() {"string1","string2"};

        if (ListToMatch.ToArray().Any(cont.Contains))
        {
            return false;
        }
        else
            return true;
    }

And usage:

List<string> ListToCheck = new List<string>() {"string1","string2","string3","string4"};
List<string> FinalList = ListToCheck.FindAll(IsContain);

The final list contains only the matched elements string1 and string2 from list to check. Can easy be switched to int List.


You can Intersect the two lists:

if (A.Intersect(B).Any())

I write a faster method for it can make the small one to set. But I test it in some data that some time it's faster that Intersect but some time Intersect fast that my code.

    public static bool Contain<T>(List<T> a, List<T> b)
    {
        if (a.Count <= 10 && b.Count <= 10)
        {
            return a.Any(b.Contains);
        }

        if (a.Count > b.Count)
        {
            return Contain((IEnumerable<T>) b, (IEnumerable<T>) a);
        }
        return Contain((IEnumerable<T>) a, (IEnumerable<T>) b);
    }

    public static bool Contain<T>(IEnumerable<T> a, IEnumerable<T> b)
    {
        HashSet<T> j = new HashSet<T>(a);
        return b.Any(j.Contains);
    }

The Intersect calls Set that have not check the second size and this is the Intersect's code.

        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in second) set.Add(element);
        foreach (TSource element in first)
            if (set.Remove(element)) yield return element;

The difference in two methods is my method use HashSet and check the count and Intersect use set that is faster than HashSet. We dont warry its performance.

The test :

   static void Main(string[] args)
    {
        var a = Enumerable.Range(0, 100000);
        var b = Enumerable.Range(10000000, 1000);
        var t = new Stopwatch();
        t.Start();
        Repeat(()=> { Contain(a, b); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//490ms

        var a1 = Enumerable.Range(0, 100000).ToList();
        var a2 = b.ToList();
        t.Restart();
        Repeat(()=> { Contain(a1, a2); });
        t.Stop();

        Console.WriteLine(t.ElapsedMilliseconds);//203ms

        t.Restart();
        Repeat(()=>{ a.Intersect(b).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//190ms

        t.Restart();
        Repeat(()=>{ b.Intersect(a).Any(); });
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//497ms

        t.Restart();
        a.Any(b.Contains);
        t.Stop();
        Console.WriteLine(t.ElapsedMilliseconds);//600ms

    }

    private static void Repeat(Action a)
    {
        for (int i = 0; i < 100; i++)
        {
            a();
        }
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>