Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query to find if items in a list are contained in another list

Tags:

c#

linq

I have the following code:

List<string> test1 = new List<string> { "@bob.com", "@tom.com" }; List<string> test2 = new List<string> { "[email protected]", "[email protected]" }; 

I need to remove anyone in test2 that has @bob.com or @tom.com.

What I have tried is this:

bool bContained1 = test1.Contains(test2); bool bContained2 = test2.Contains(test1); 

bContained1 = false but bContained2 = true. I would prefer not to loop through each list but instead use a Linq query to retrieve the data. bContained1 is the same condition for the Linq query that I have created below:

List<string> test3 = test1.Where(w => !test2.Contains(w)).ToList(); 

The query above works on an exact match but not partial matches.

I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.

like image 280
cjohns Avatar asked Sep 29 '12 21:09

cjohns


People also ask

How to check list contains on another list in linq?

If you have a list, which is an IEnumerable, and a list2, which is a List<T>, with Linq, you can do it like this: bool containsCommonItem = list. Any(x => list2. Contains(x));

Where with Contains in Linq?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.


1 Answers

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0); 

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1))); 
like image 188
Giscard Biamby Avatar answered Sep 21 '22 16:09

Giscard Biamby