C# 使用 Linq 检查列表中的字符串是否包含特定字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9032655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:41:22  来源:igfitidea点击:

Check if a string within a list contains a specific string with Linq

c#linq

提问by Saeid Yazdani

I have a List<string>that has some items like this:

我有一个List<string>有一些这样的项目:

{"Pre Mdd LH", "Post Mdd LH", "Pre Mdd LL", "Post Mdd LL"}

Now I want to perform a condition that checks if an item in the list contains a specific string. something like:

现在我想执行一个条件来检查列表中的项目是否包含特定字符串。就像是:

IF list contains an item that contains this_string

IF list contains an item that contains this_string

To make it simple I want to check in one go if the list at least! contains for example an item that has Mdd LHin it.

为了简单起见,我想至少在列表中检查一次!包含例如一个项目Mdd LH

I mean something like:

我的意思是这样的:

if(myList.Contains(str => str.Contains("Mdd LH))
{
    //Do stuff
}

Thanks.

谢谢。

采纳答案by Jon Skeet

I think you want Any:

我想你想要Any

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

熟悉LINQ 标准查询运算符是非常值得的;我通常会使用那些而不是特定于实现的方法(例如List<T>.ConvertAll),除非我真的被特定运算符的性能所困扰。(通过了解结果的大小等,特定于实现的方法有时会更有效。)

回答by ?yvind Br?then

Thast should be easy enough

这应该很容易

if( myList.Any( s => s.Contains(stringToCheck))){
  //do your stuff here
}

回答by slugster

Try this:

尝试这个:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any()will stop searchingthe moment it finds a match, so is quite efficient for this task.

Any()停止搜索找到一个匹配的时刻,所以是这个任务相当有效率。

回答by sll

LINQ Any() would do the job:

LINQ Any() 可以完成这项工作:

bool contains = myList.Any(s => s.Contains(pattern));

Any(), MSDN:

任何(),MSDN

Determines whether any element of a sequence satisfies a condition

确定序列的任何元素是否满足条件

回答by Rafael Diego Nicoletti

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

如果您使用包含,您可能会得到误报。假设您有一个包含这样文本的字符串:“My text data Mdd LH” 使用 Contains 方法,此方法将返回 true 以供调用。方法是使用等于运算符:

bool exists = myStringList.Any(c=>c == "Mdd LH")

bool exists = myStringList.Any(c=>c == "Mdd LH")