Search in List (Of String) - Case insensitive

4

How do you search for String on List(Of String) without considering the case? I am using .net 2.0.

Contains does not allow you to pass any additional parameters. I tried to use Find but it also did not work.

Dim v_list As New List(Of String)(New String() {"a", "b", "c"})
Dim v_contains As Boolean
v_contains = v_list.Contains("A")
v_contains = v_list.Find(Function(x) String.Compare(x, "A", True))
    
asked by anonymous 22.10.2015 / 14:19

3 answers

2

Does not the Exists serve?

    Dim v_list As New List(Of String)(New String() {"a", "b", "c"})
    Dim v_contains As Boolean
    v_contains = v_list.Exists(Function(x) String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) = 0)

or if you use Find

Dim find = v_list.Find(Function(x) String.Compare(x, "A", StringComparison.OrdinalIgnoreCase) = 0)
    
22.10.2015 / 19:43
3

The issues I see in this code:

  • The Find method will return an item from the list, therefore a String. But you declared v_contains as Boolean.
  • The predicate of Find would need to return a Boolean value, but it is not what String.Compare does (it returns a positive, negative, or zero number).

One possible solution:

Dim v_list As New List(Of String)(New String() {"a", "b", "c"})
Dim v_contains As String
v_contains = v_list.Find(Function(x) x.ToUpper() = "A") ' "a"
    
22.10.2015 / 14:39
0

The accepted solution was not working for my Web application, although it works normally in a console application. The solution found was to use AddressOf instead of putting the inline function.

Below is Default.aspx.vb:

Imports System.Collections.Generic
Partial Class _Default
    Inherits System.Web.UI.Page

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim list As New List(Of String)
        Dim exists As Boolean

        list.Add("B")
        list.Add("A")

        exists = list.Exists(AddressOf check)
    End Sub

    Private Shared Function check(ByVal s As String) As Boolean
        Return String.Compare(s, "a", StringComparison.OrdinalIgnoreCase) = 0
    End Function
End Class
    
23.11.2015 / 17:52