Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.
I would like to add an extending answer referring to different C# versions and because of two reasons:
The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.
No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).
Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.
Since .NET 3.5 there also exists a generic method Array<T>.Exists()
:
public void PrinterSetup(string[] printer)
{
if (Array.Exists(printer, x => x == "jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:
// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
if (printer.ArrayContains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
}
}
public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
// If you want this to find "null" values, you could change the code here
return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}
In this case this ArrayContains()
method is used and not the Contains method of Linq.
The elsewhere mentioned .Contains methods refer to List<T>.Contains
(since C# 2.0) or ArrayList.Contains
(since C# 1.1), but not to arrays itself directly.