Ivan Toporivschi
Ivan Toporivschi

Reputation: 3

Can I check if a string contains an array's element in it?

Trying to find the more efficient way to check if a string contains words(strings) from an array.

I have a list of strings. When I'm looping through them, I want to check if the current string has some specific words in it. For storing those words I use an array of strings. So, I was wondering if there was a way with linq?(or just more efficient way) Something like string.Any() for strings?

I did it with loops, but I don't personally like it: First of all, the main list and array:

List<string> lista = new List<string>() {"\r\n", "<p>This is a paragrath</p>", "<h2>This is a subheader</h2>", "\r\n" };
string[] arr = new string[] {"<h1>","<h2>","<h3>","<p>" };

Now I go into the loops:

for(int i = 0; i < lista.Count; i++)
{
  if(lista[i] != "\r\n")
    for(int j = 0; j < arr.Length; j++)
    {
      if(lista[i].Contains(arr[j]))
      {
        ...
      }
    }
}

As I've said above, I don't like it this way. Is there any other method?

Upvotes: 0

Views: 90

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

This will give you all items in lista which at least contains one element of arr:

string[] result = lista.Where(x => arr.Any(a => x.Contains(a)).ToArray()

Upvotes: 3

Filip Cordas
Filip Cordas

Reputation: 2561

Written in linq syntax I think it's a bit more readable.

var allThatContainTags = from html in lista
                         where html != "\r\n" && arr.Any(html.Contains)
                         select html;

Upvotes: 0

Related Questions