'Compare list of string with string in linq

I have list of string Like list1 contain 'pinky','smita','Rashmi','Srivani' And string is like String str = "pinky, Nandini' I want to check if neither of str present in list1,proceed further. how to do that?



Solution 1:[1]

If I understood correctly, you want to return false in the example case, so you can use Any method: Check if none of the elements of the list is already in the str, here is a one liner:

if (!list.Any(x=>str.Contains(x))) ....

Solution 2:[2]

You can use combination of .Any() with .Contains() with !,

var list1 = new List<string>(){ "pinky", "smita", "Rashmi", "Srivani" };
string str = "pinky, Nandini";
var list2 = str.Split(",");

var nameExists = list2.Any(x => list1.Contains(x));
if(!nameExists)
{
   //Your code goes here.
}

As @Fildor said, you can use Intersect(). Elegant approach,

//All credit goes to @Fildor
var nameExists = list1.Intersect(list2).Any(); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saeed Amiri
Solution 2