zsharp
zsharp

Reputation: 13756

How to check if any words in a list contain a partial string?

    var list=alist.Contains("somestring")

this matches whole string, how to see if any word in list has a substring matching "somestring"?

Upvotes: 15

Views: 18897

Answers (2)

mythz
mythz

Reputation: 143284

var hasPartialMatch = alist.Split(' ').ToList()
      .Any(x => x.Contains("somestring"));

Upvotes: -1

Reed Copsey
Reed Copsey

Reputation: 564323

You can use the Enumerable.Any method:

bool contained = alist.Any( l => l.Contains("somestring") );

This is checking each element using String.Contains, which checks substrings. You previously were using ICollection<string>.Contains(), which checks for a specific element of the list.

Upvotes: 35

Related Questions