Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 805
Laura Bejjani Avatar asked Jul 05 '17 04:07

Laura Bejjani


4 Answers

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";
}
like image 75
Yeldar Kurmangaliyev Avatar answered Nov 15 '22 13:11

Yeldar Kurmangaliyev


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";
}
like image 20
Nikhil Agrawal Avatar answered Nov 15 '22 14:11

Nikhil Agrawal


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

like image 38
umasankar Avatar answered Nov 15 '22 15:11

umasankar


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
    }
like image 22
Preet Avatar answered Nov 15 '22 15:11

Preet