Check if a value is in an array (C#)
Solution 1
Add necessary namespace
using System.Linq;
Then you can use linq Contains()
method
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}
Solution 2
Add using System.Linq;
at the top of your file. Then you can do:
if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{
}
Solution 3
public static bool Contains(Array a, object val)
{
return Array.IndexOf(a, val) != -1;
}
Solution 4
Something like this?
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
PrinterSetup(printer);
// redefine PrinterSetup this way:
public void PrinterSetup(string[] printer)
{
foreach (p in printer.Where(c => c == "jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}
}
Solution 5
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.
Related videos on Youtube
Steven Matthews
Updated on June 15, 2022Comments
-
Steven Matthews less than a minute
How do I check if a value is in an array in C#?
Like, I want to create an array with a list of printer names.
These will be fed to a method, which will look at each string in turn, and if the string is the same as a value in an array, do that action.
For example:
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"}; foreach (p in printer) { PrinterSetup(p); }
These are the names of the printers, they are being fed to the PrinterSetup method.
PrinterSetup will look sort of like this (some pseudocode):
public void PrinterSetup(printer) { if (printer == "jupiter") { Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"); } }
How do I format
if (printer == "jupiter")
in a way that C# can recognize?-
Jon Skeet over 9 yearsTry giving your parameter name a type (string) and it will be fine.
-
newfurniturey over 9 yearsI'm kind of confused as the question. Are you asking how to check if a value is in an array, or how to do string-comparison in C#? If it's the latter, you would use
printer.Equals("jupiter")
. If it's the former, uselinq
andprinter.Contains("jupiter")
-
-
kaz about 7 yearsThis is a general example - can you provide one that matches the question better?
-
Jeppe Stig Nielsen over 5 yearsI like this. However, it will fail if
a
is a multidimensional array (such asnew string[10, 20, 15]
for example), with an exception. It will also fail with one-dimensional arrays that are not indexed from zero (such asArray.CreateInstance(typeof(string), new[] { 5, }, new[] { -2, })
, rare in C# I admit), with a possibly wrong return value. These shortcomings are easy to fix with generics:public static bool Contains<TElement>(TElement[] a, TElement val) { return Array.IndexOf(a, val) != -1; }
-
Grant Birchmeier almost 5 yearsIt may be a general example, but it's exactly what I was looking for.
-
peter.cyc about 2 yearsI suggest to change name to ArrayContains() to avoid confusion with the Linq Contains()
-
Philm almost 2 yearsI´ve done this, although there are also arguments against: It is the basic idea of polymorphism to use the same name for different data types, Especially with a Linq-setting in mind. Using different names is not polymorph. But readibility and avoiding misunderstandings shall win, I think, so, yes.