如何从 Enumerable.Any 和 List.Contains 比较中获取字符串值?

How to get the string value from a Enumerable.Any and List.Contains comparison?

我有 2 个字符串列表,我正在检查列表 1 是否包含列表 2 中的任何项目。

if (List2.Any(s => List1.Contains(s)))
{ //do stuff 
}

如果找到一个字符串,我想记录它,但我找不到从上面的代码中获取 S 值的方法。

当我尝试写出 'S' 作为字符串的变量时,它不被识别为一个。

如何从上面的比较中得到 S 的值?

此外 - 我无法弄清楚如何用文字具体表达我对标题的追求。如果您有关于如何 re-write 标题的建议,我愿意接受。我希望它对问题是准确的。

此 Linq 将在一行中完成您需要的工作

if ((from s in List2 from s1 in List1 where s == s1 select s).Any())
{
  //do stuff 
}

Enumerable.Any 并不是要获取所发现的内容,而只是 找到了某些内容

如果你也想要what was found,我相信你应该使用Enumerable.FirstOrDefault:

string result = list2.FirstOrDefault(s => list1.Contains(s));

if(!string.IsNullOrEmpty(result))
{
    // do stuff...
}

另一方面,如果你想要所有的巧合,你应该使用Enumerable.Intersect:

IEnumerable<string> allCoincidences = list2.Intersect(list1);