J01337
J01337

Reputation: 58

How can I check whether my list contains a string with a certain condition

I was wondering if there can be written something like this:

List<string> list;
string sub;
if( list.Contains( s=>s.Contains(sub) ) ) {
    //do something
}

what I want here in the code is to see if the list<string> list contains string s with a certain substring string sub which I would previously set to a value

thanks in advance

Upvotes: 2

Views: 1673

Answers (3)

Drag and Drop
Drag and Drop

Reputation: 2734

list.Contains("foo"), in this code the Enumerable.Contains method checks if the list contains the specified element. An exact match.

What you want is either :

1/. Select the elements that match a sub pattern : Where

var elementsWithSubPattern = list.Where(s => s.Contains(sub)); 

2/. Check if there are any element in this list that match the sub pattern: Any

bool anyMatch = list.Any(s => s.Contains(sub)); 

3/. Check if all the elements match the sub pattern: All

bool allMatch = list.All(s => s.Contains(sub)); 

Upvotes: 0

Jeswin Rebil
Jeswin Rebil

Reputation: 460

You can use like below

var newList = list.Where(x=>x.Contains(sub)).ToList();
if(newList != null && newList.Count> 0){
   //Do something here
}

it will return the list of string contains sub

Upvotes: 1

Isitar
Isitar

Reputation: 1449

it can be done using linq

list.Where(s => s.Contains(sub))

this gives you a list with all strings containing the substring.

If you just want to check if any of the strings contains the substring, you can use the method Any

if (list.Any(s => s.Contains(sub))) {...

Upvotes: 9

Related Questions