3

Hi there is there a way to check specific integer array indexes for specific numbers in C#; for example what I would love to have worked would be:

    if(si[6] || si[7] || si[8] == 3)
     {
      MessageBox.Show("3 detected")
     }
    else
    {
     continue();
    {

Obviously this doesn't work. Is there a clean way to do this? Thank you for looking.

4

4 回答 4

10
var indexes = new int[] {6, 7, 8};
if (indexes.Any(i => si[i] == 3))
{
    MessageBox.Show("3 detected")
}
于 2012-11-05T14:34:48.103 回答
5

最简单的方法是进行三个单独的检查:

if (si[6] == 3 || si[7] == 3 || si[8] == 3)
于 2012-11-05T14:32:09.883 回答
1

您可以使用带有参数的方法更简洁地执行此操作:

public static bool HasValue(int value, params int[] itemsToCheck)
{
    bool valueDetected = false;
    foreach(var item in itemsToCheck)
    {
        valueDetected |= item == value;
    }

    return valueDetected;
}

然后你可以这样称呼它:

if (HasValue(3, si[6], si[7], si[8]))
{

}
于 2012-11-05T14:40:27.220 回答
1

您可以使用 Array.IndexOf 函数来查找整数的索引。如果数组有整数,那么它将返回索引,否则它将返回-1。

像这样 int[] a = new int[] { 1, 2 }; int c = Array.IndexOf(a, 2);

于 2012-11-05T14:44:14.620 回答