Check if a value is in an array (C#)
public static bool Contains(Array a, object val)
{
return Array.IndexOf(a, val) != -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"");
}
Add using System.Linq;
at the top of your file. Then you can do:
if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{
}
string[] array = { "cat", "dot", "perls" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perls");
bool b = Array.Exists(array, element => element == "python");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));
// Display bools.
Console.WriteLine(a); // true
Console.WriteLine(b); // false
Console.WriteLine(c); // true
Console.WriteLine(d); // false