检查的值是一个数组(C#)
问题描述:
我如何检查,如果一个值是一个数组在C#?
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.
例如:
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
foreach (p in printer)
{
PrinterSetup(p);
}
这些是打印机的名称,它们被馈送到PrinterSetup方法
These are the names of the printers, they are being fed to the PrinterSetup method.
PrinterSetup看起来有几分像这样(一些伪code):
PrinterSetup will look sorta like this (some pseudocode):
public void PrinterSetup(printer)
{
if (printer == "jupiter")
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}
}
我如何格式化如果(打印机==朱庇特){
的方式,C#可以识别?
How do I format if (printer == "jupiter") {
in a way that C# can recognize?
答
添加必要的命名空间
using System.Linq;
然后你可以使用LINQ 包含()
方法
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}