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.
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));
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.
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.
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With