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

Raj*_*hra 1 c# console-application

我想在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.");
      }
    }
Run Code Online (Sandbox Code Playgroud)

这种结果有解决方案吗?

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

Jon*_*eet 6

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)