Andy Williams
Andy Williams

Reputation: 907

Check if any element in an array matches my condition

I've got an array with 2 values in it. I want to use an If statement to see whether any of the values in the array equals the SelectedValue of my DropDown.

So far, everything I've tried only gives negative results (only the Else condition is reached):

Dim twoValues() As String = {"one", "two"}

If Me.ddlDropdown.SelectedValue.ToLower.Equals(twoValues.Any) Then
    'do something
Else
    'do something else
End If

Upvotes: 1

Views: 965

Answers (1)

Jimi
Jimi

Reputation: 32288

You can invert the comparison and use LINQ's Any() method to compare elements of the array to the provided value, until a matching value is found.
Since the comparison needs to be case-insensitive, you can use the overload of String.Equals() that accepts a StringComparison argument.

Better avoid ToLower() without a CultureInfo selector when a case-insensitive comparison is needed.
Also, the InvariantCulture may apply or not, depending on the languages involved in the comparison.
If the current language is the local language and cannot be directly associated with the InvariantCulture, use StringComparison.CurrentCultureIgnoreCase instead. Or build a custom comparer.

Dim twoValues As String() = {"one", "two"}
Dim value = Me.ddlDropdown.SelectedValue.ToString()

If twoValues.Any(Function(s) s.Equals(value, StringComparison.InvariantCultureIgnoreCase)) Then
  'do something
Else
   'do something else
End If

Upvotes: 2

Related Questions