Laura Bejjani
Laura Bejjani

Reputation: 151

C# String Array Contains

Can someone explain to me why the top part of the code works but when test is an array it doesn't?

string test = "Customer - ";
if (test.Contains("Customer"))
{
    test = "a";
}

The code below doesn't work

string[] test = { "Customer - " };
if (test.Contains("Customer"))
{
    test[0] = "a";
}

Upvotes: 12

Views: 28905

Answers (4)

Preet
Preet

Reputation: 994

Because in second case your if condition is false as you are searching for first string in array of strings. Either you can use any keyword to search for any string in array that match customer or you can search test[0] to search first string in array if it matches to customer like:

if (test[0].Contains("Customer"))
    {
        //your rest of the code here
    }


 if (test.Any(x => x.Contains("Customer")))
    {
        //your rest of the code here
    }

Upvotes: 1

umasankar
umasankar

Reputation: 607

string test = "Customer - ";
if (test.Contains("Customer"))
{
  test = "a";
}

In this Contains is a String Class Method it's base of IEnumerable checks

"Customer -" having Customer.

But

string[]test = { "Customer - " };
if (test.Contains("Customer"))
{
   test[1]= "a";
 }

In this Place Contains is a IEnumerable Method it's base of IEnumerable checks.So, It's Not Working You Change the Code

string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{

}

test[1]="a" It's throw Exception because, the array position start with 0 not 1

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

First snippet searches for string Customer inside another string Customer - which works but in second snippet string Customer is searched inside array of strings one of which is Customer -. Hence the second returns false.

This is evident from how you declare test

string test = "Customer - ";

OR

string[] test = { "Customer - " };

Notice the curly brackets. That's how you define a collection (array here)

To make second snippet work you should do

string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{
    test[1] = "a";
}

Upvotes: 3

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

In first case, you call String.Contains which checks if string contains substring.
So, this condition returns true.

In the second case, you call Enumerable.Contains on string[] which checks if string array contains a specific value.
Since there is no "Customer" string in your collection, it returns false.

These are two similarly called but actually different methods of different types.

If you want to check if any string in collection contains "Customer" as a substring, then you can use LINQ .Any():

if (test.Any(s => s.Contains("Customer"))
{
    test[1] = "a";
}

Upvotes: 16

Related Questions