Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Trick when using Array.Contains()

Rate me:
Please Sign up or sign in to vote.
5.00/5 (14 votes)
13 Jun 2011CPOL 13.5K   5   6
The Array class already contains this capability with no casting required. The IndexOf method is a static one that returns the index of the value and a -1 if it doesn't exist.Here is an example:exists = Array.IndexOf(arr, "item") >= 0

The Array class already contains this capability with no casting required. The IndexOf method is a static one that returns the index of the value and a -1 if it doesn't exist.


Here is an example:


C#
exists = Array.IndexOf(arr, "item") >= 0

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSimpler and nice one. If we do not want exact matching and i... Pin
Mohammad A Rahman27-Jun-11 18:48
Mohammad A Rahman27-Jun-11 18:48 
GeneralReason for my vote of 1 Could be problem when finding word i... Pin
sachin10d20-Jun-11 21:56
sachin10d20-Jun-11 21:56 
GeneralRe: You are incorrect. Try this: string[] arr = new[] {"item4", ... Pin
JV999920-Jun-11 22:23
professionalJV999920-Jun-11 22:23 
GeneralReason for my vote of 5 This alternative is even nicer. Than... Pin
w.a.g.i20-Jun-11 20:02
w.a.g.i20-Jun-11 20:02 
GeneralReason for my vote of 5 Simpler and just as clear. Pin
Ben Robbins20-Jun-11 14:52
Ben Robbins20-Jun-11 14:52 
GeneralArray.IndexOf(arr, "item") >= 0 This will return the exact m... Pin
Kiran Sonawane13-Jun-11 4:00
Kiran Sonawane13-Jun-11 4:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.