简体   繁体   English

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

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

I have 2 string lists that I am checking if List 1 contains any of the items in List 2. 我有2个字符串列表,我正在检查列表1是否包含列表2中的任何项目。

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

If a string is found, I am wanting to log it, but I cannot find a way to get the value of S from the above code. 如果找到一个字符串,我想将其记录下来,但是我找不到从上述代码中获取S值的方法。

When I try to write out 'S' as a variable for a string, it isn't recognized as one. 当我尝试将“ S”写为字符串的变量时,无法将其识别为一个。

How can I get the value of S from my above comparison? 如何从上述比较中得出S的值?

Also - I couldn't figure out how to put into words specifically what I was after for the title. 另外-我想不通如何用词明确表达我对标题的追求。 If you have a recommendation on how to re-write the Title, I'm open to it. 如果您有关于如何重写标题的建议,我欢迎您。 I'd like it to be accurate for the question. 我希望这个问题准确无误。

Enumerable.Any isn't meant to get what's being found but just that something was found . Enumerable.Any并不是要得到被发现的东西,而仅仅是找到了东西

If you also want what was found , I believe you should use Enumerable.FirstOrDefault : 如果您还想要找到什么 ,我相信您应该使用Enumerable.FirstOrDefault

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

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

In the other hand, if you want all coincidences, you should use Enumerable.Intersect : 另一方面,如果需要所有巧合,则应使用Enumerable.Intersect

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

This Linq will do what you need in just one line Linq只需一行即可满足您的需求

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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