Home > Software engineering >  How to use Contains method to search within another collection?
How to use Contains method to search within another collection?

Time:06-21

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));

CodePudding user response:

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

CodePudding user response:

You should use Intersect:

IEnumerable<int> both = numberList.Intersect(numberListEnhanced);

Check this: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.intersect?view=net-6.0

  • Related