Click here to Skip to main content
11,480,938 members (52,857 online)
Click here to Skip to main content

Tagged as

Trick when using Array.Contains()

, 13 Jun 2011 CPOL 4.9K 5
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

Ctznkane

United States United States
No Biography provided

Comments and Discussions

 
GeneralSimpler and nice one. If we do not want exact matching and i... Pin
Mohammad A Rahman27-Jun-11 19:48
memberMohammad A Rahman27-Jun-11 19:48 
GeneralReason for my vote of 1 Could be problem when finding word i... Pin
sachin10d20-Jun-11 22:56
groupsachin10d20-Jun-11 22:56 
GeneralRe: You are incorrect. Try this: string[] arr = new[] {"item4", ... Pin
JV999920-Jun-11 23:23
memberJV999920-Jun-11 23:23 
You are incorrect. Try this:
string[] arr = new[] {"item4", "test", "item 3", "item", "beer"};

int index = Array.IndexOf(arr, "item");
bool exists = Array.IndexOf(arr, "item") >= 0;

The returned index will always be 3 and if you remove "item", the index will be -1.

Voted 5 for this solution. Very elegant, I wouldn't have thought of that method Smile | :)
GeneralReason for my vote of 5 This alternative is even nicer. Than... Pin
w.a.g.i20-Jun-11 21:02
memberw.a.g.i20-Jun-11 21:02 
GeneralReason for my vote of 5 Simpler and just as clear. Pin
Ben Robbins20-Jun-11 15:52
memberBen Robbins20-Jun-11 15:52 
GeneralArray.IndexOf(arr, "item") >= 0 This will return the exact m... Pin
Kiran Sonawane13-Jun-11 5:00
memberKiran Sonawane13-Jun-11 5:00 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 13 Jun 2011
Article Copyright 2011 by Ctznkane
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid