Spartaok
Spartaok

Reputation: 309

How to use StartsWith with an array of string?

Suppose I have an array of strings:

var array = new string[] {"A", "B"}.

Then I want check if the following string: "boca" starts with the letter included in the array.

What I did is:

var result = "boca".StartsWith(array);

but the method doesn't not accept an arra as argument but a single string

Upvotes: 3

Views: 3772

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 41018

You have to loop the array and check if the word starts with anything in the array. Something like this:

var result = array.Any(s => "boca".StartsWith(s));

Assuming your array is {"A", "B"}, then result will be false, because StartsWith is case-sensitive by default.

If you want it case-insensitive, then this will work:

var result = array.Any(s => "boca".StartsWith(s, StringComparison.CurrentCultureIgnoreCase));

In this case, result will be true.

Upvotes: 3

Related Questions