C# 中有什么选项具有与 SQL 中的 'IN' 相同的功能?

What is the option in C# having the same capability like 'IN' in SQL?

我想在 if 条件块中搜索多个条件 - 与 SQL 中的 IN 运算符相同。

public class Check{

    int [] arr = {1, 2, 5, 9, 7, 11, 89};
    for (int i=0; i<arr.length; i++)
    {
      if(arr[i]==1||arr[i]==5||arr[i]==7||arr[i]==89)
      {
        Console.WriteLine("The number was found.");
      }
    }

Is there a solution for this kind of result?

if (arr[i] in(1, 5, 7, 89)
{
    Console.WriteLine("The No Is Found.");
}

C# 作为一种 语言 中没有任何东西等同于 IN,不...但是您可以轻松实现类似的效果。

最简单的方法可能是对数组使用 System.LinqContains

using System;
using System.Linq;

public class Check{

    static void Main()
    {
        int[] candidates = {1, 2, 5, 9, 7, 11, 89};
        // This is the members of the "in" clause - the
        // the values you're trying to check against
        int[] targets = { 1, 5, 7, 89 };
        foreach (int candidate in candidates)
        {
            Console.WriteLine(
                targets.Contains(candidate) ?
                $"{candidate} is in targets" :
                $"{candidate} is not in targets");
        }
    }
}

或者,您可以使用 HashSet<int> - 如果您有大量目标,那会更有效:

using System;
using System.Collections.Generic;

public class Check{

    static void Main()
    {
        int[] candidates = {1, 2, 5, 9, 7, 11, 89};
        var targets = new HashSet<int> { 1, 5, 7, 89 };
        foreach (int candidate in candidates)
        {
            Console.WriteLine(
                targets.Contains(candidate) ?
                $"{candidate} is in targets" :
                $"{candidate} is not in targets");
        }
    }
}