Dumbo
Dumbo

Reputation: 14142

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

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

{"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

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

I mean something like:

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

Upvotes: 24

Views: 137934

Answers (5)

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60724

That should be easy enough

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

Upvotes: 14

slugster
slugster

Reputation: 49985

Try this:

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

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

Upvotes: 9

Rafael Diego Nicoletti
Rafael Diego Nicoletti

Reputation: 473

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:

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503290

I think you want 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.)

Upvotes: 83

sll
sll

Reputation: 62544

LINQ Any() would do the job:

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

Any(), MSDN:

Determines whether any element of a sequence satisfies a condition

Upvotes: 7

Related Questions