Night Monger
Night Monger

Reputation: 780

how to check string.contains Either Ways

How do i see if string1 contains string2 OR string2 contains string1 OR String 3 contains string 1 OR String 1 contains string 3 OR String 2 contains string 3 OR string 3 contains String 2 in single line?

like i want to do

if ( string1.contains(string2) || string2.contains(string1) || string3.contains(string1) string3.contains(string2) || .. and so on.. ) 
{

}

in single check without or clause. In reality, i have to do this check multiple times and multiple places. So just wondering if there is a better way.

I have updated my business logic or the reason for this logic. We have 6 Sites and we will get just the page names of the sites. i have to check the site names are similar. The only problem is.. i donot get the site names in any particular pattern. like for eg:

String1 = "/search-results"
string2= "www.foo.com/search-results?Id=1234"
string3 = "search-results"
string4= "/search-results?Id=1234"

and if you look at my values, you will note that if you compare any two strings with OR clause.. they will be true.

Upvotes: 0

Views: 620

Answers (2)

Toto
Toto

Reputation: 7719

You can have an helper method and use it :

public static void SomeContainsAnOther(this IEnumerable<string> @this)
{
   @this.Any(v=>@this.Count(other=>other.Contains(v)) > 1);
}

And use it :

new string[] {string1,string2,string3,..stringN}.SomeContainsAnOther();

Upvotes: -1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Put your strings into an array or a list, then:

bool result = yourStrings
            .Where((x, idx) => 
                yourStrings.Where((y, index) => idx != index && x.Contains(y))
                .Any())
                .Any();

Explanation:

This query will take each string, and compare them with others and returns a result that indicates whether any of the strings is contains another string in the collection.

For example consider we have three strings foo, bar and fooBar, the steps would be like the following:

  1. Take "foo" and check if it contains bar or fooBar (false)
  2. Take "bar" and check if it contains foo or fooBar (false)
  3. Take "fooBar" and check if it contains foo or bar (true because of foo)

I wish there is an overload of Any that accepts the index parameter...

Edit: here is also more efficient implementation for larger collections:

public static bool ContainsAny(IList<string> source)
{
     int count = source.Count;
     for (int i = 0; i < count; i++)
     {
          for (int j = 0; j < count; j++)
          {
              if (i != j && source[i].Contains(source[j]))
              {
                  return true;
              }
          }
      }

      return false;
}

Upvotes: 3

Related Questions