Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 } 

Thanks.

like image 996
Saeid Yazdani Avatar asked Jan 27 '12 11:01

Saeid Yazdani


People also ask

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

How do you check if a list contains a string in C #?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

How do you check whether a list contains a specified element?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you check if a string is present in a list of strings in Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


2 Answers

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.)

like image 104
Jon Skeet Avatar answered Sep 21 '22 15:09

Jon Skeet


Thast should be easy enough

if( myList.Any( s => s.Contains(stringToCheck))){   //do your stuff here } 
like image 37
Øyvind Bråthen Avatar answered Sep 23 '22 15:09

Øyvind Bråthen