C# & Unity - Searching an array for a value and return true/false [duplicate]
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:
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
Solution 3:
Add using System.Linq;
at the top of your file. Then you can do:
if ((new [] {"foo", "bar", "baaz"}).Contains("bar"))
{
}
Solution 4:
public static bool Contains(Array a, object val)
{
return Array.IndexOf(a, val) != -1;
}
Solution 5:
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"");
}
}