检查值是否在数组中(C#) [英] Check if a value is in an array (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 看起来像这样(一些伪代码):
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");
}
}
如何以 C# 可以识别的方式格式化 if (printer == "jupiter")
?
How do I format if (printer == "jupiter")
in a way that C# can recognize?
推荐答案
添加必要的命名空间
using System.Linq;
然后就可以使用linq的Contains()
方法
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"");
}
这篇关于检查值是否在数组中(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!