简体   繁体   中英

Compare list of string with string in linq

我有字符串列表 Like list1 contains 'pinky','smita','Rashmi','Srivani' 字符串就像 String str = "pinky, Nandini' 我想检查 list1 中是否没有 str 存在,继续进行。怎么做?

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

如果我理解正确,您想在示例情况下返回 false,因此您可以使用Any方法:检查列表中的所有元素是否已经在str中,这是一个单行:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM