Search code examples
c#linqcontains

How to use Contains method to search within another collection?


I have a list of int.

List<int> numberList = new List<int>() { 1, 2, 3, 4, 8, 10, 2};

Now, I have another list of int

List<int> numberListEnhanced = new List<int>() { 1, 2, 3, 5, 6};

I have a LINQ query in which I am using WHERE and in that I need to check if numberListEnhanced contains the elements of the numbersList.

I have done for a single but for multiple cannot figure out.

For single:

.....where numberListEnhanced.Contains((int)s.Id));

Solution

  • You can use Intersect (no duplicates):

    var valuesInBothLists = numberList.Intersect(numberListEnhanced).ToList(); 
    
    // result: 1 2 3
    

    Or you can do this using Where:

    var valuesInBothLists = numberList.Where(item => numberListEnhanced.Contains(item)).ToList();
    
    // or 
    
    var valuesInBothLists = from item in numberList
                            where numberListEnhanced.Contains(item)
                            select item;
    
    // result: 1 2 3 2