Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to do a contains with string[]

Tags:

c#

I am getting back a "string[]" from a 3rd party library. I want to do a contains on it. what is the most efficient way of doing this?

like image 504
leora Avatar asked Nov 30 '22 20:11

leora


2 Answers

Array.IndexOf:

bool contains = Array.IndexOf(arr, value) >= 0;

Or just use LINQ:

bool contains = arr.Contains(value);

LINQ should be "fast enough" for most purposes.

like image 76
Marc Gravell Avatar answered Dec 09 '22 20:12

Marc Gravell


If you are only checking a single time, use Array.IndexOf or the LINQ Contains method like Marc proposed. If you are checking several times, it might be faster to first convert the string array into a HashSet<string>.

like image 38
Rauhotz Avatar answered Dec 09 '22 21:12

Rauhotz