Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a list of large number of string elements in array and i am using contains function to check if it contains that element. it is working fine. Now i want to get to know the index/position of element. suppose the array is
C#
dim s as string() = {"first", "second","third"}
and the string

dim l as string = "third"
method

dim b as boolean = s.Contains(l, StringComparer.CurrentCultureIgnoreCase)
flag

if (b) Then
messagebox.show("It exists") 
end if
Posted
Updated 6-Apr-15 1:24am
v2

1 solution

Use Array.IndexOf. With this method, you don't even need Contains: IndexOf returns -1 if the item doesn't exist:
VB.NET
Dim s As String() = {"first", "second", "third"}
Dim l As String = "third"
Dim i As Integer = Array.IndexOf(s, l)
If i >= 0 Then
    Console.WriteLine("it exists at index " + i.ToString())
End If

Important: if you want to use StringComparer.CurrentCultureIgnoreCase, then you cannot use the above; you'll have to use FindIndex in that case:
VB.NET
Dim i As Integer = Array.FindIndex(s, Function(x As String) x.Equals(l, StringComparison.CurrentCultureIgnoreCase))
 
Share this answer
 
Comments
Sahilmanchanda 6-Apr-15 7:53am    
@ProgramFOX. i am using your second option. but it is giving my array index out of range exception
Thomas Daniels 6-Apr-15 7:56am    
Hmm... it works fine for me. Do you use i as an array index later? In that case, you can get that error if the index is -1.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900