views:

398

answers:

6

I'm using .NET 2.0 I have a large array of string. I want to check whether a particular string is there in the array or not, I'm not sure, whether following code is optimized or I need to make it more optimized. please guide.

string []test_arr= new string[]{"key1","key2","key3"};
Boolean testCondition = (new List<string>(test_arr)).Contains("key3");

I also wants to know more about

  1. .NET Generics
  2. .NET Attributes
  3. .NET Reflections

is there any good reference or book, that someone has already refer then help me out !

+6  A: 
string []test_arr= new string[]{"key1","key2","key3"};
bool testCondition = Array.Exists
(
    test_arr,
    delegate(string s) { return s == "key3";}
);
Matt Howells
+1, but your delegate body should be `return s == "key3";`
LukeH
Thanks Luke, was writing from memory. I have corrected the code.
Matt Howells
You probably mixed Lamda and delegate notation ;).
Dykam
+2  A: 

If its possible you could sort your array (using static Array.Sort method) and then use Array.BinarySearch

Alternatively you need to use a more optimised data structure for your strings.

Grzenio
+1  A: 

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces.

Hence you can do the following:

string[] test_arr = new string[]{"key1","key2","key3"};
Boolean testCondition = ((IList<string>)test_arr).Contains("key3");
Winston Smith
+1  A: 

List is O(n), SortedList is O(log n)

astander
+1  A: 

abouot your larga array of string: there is no optimized way as long as you use an array (you have to start at the first element and go through each until you find it - or go through the whole array if you dont) - this gives you a worst case time of O(n) (O notation gives the time a program needs to accomplish something).

Since you want to optimize for search I suggest you use a hashtable or tree instead (depending on how large your dataset is). This will greatly reduce the time you need to check

Niko
+1  A: 

My answer very similar to Matt Howells. But I'm suggesting to use StringComparison


Array.Exists<string>(stringsArray,
                delegate(string match)
                {
                    return match.Equals("key", StringComparison.InvariantCultureIgnoreCase)
                });
Tadas