How do you implement the equivalent of SQL IN() using .net

前端 未结 9 1456
春和景丽
春和景丽 2020-12-09 16:24

In .net (c# or vb) expressions, how would you implement SQL\'s handy IN() functionality?

i.e. value in (1, 2, 4, 7)

rather than:

value = 1 or value =

相关标签:
9条回答
  • 2020-12-09 16:31

    Or using System.Linq...

    (VB.NET)

    Enumerable.Contains({1, 2, 4, 7}, value)
    

    or

    {1, 2, 4, 7}.Contains(value)
    

    (C#)

    Enumerable.Contains(new int[]{1, 2, 4, 7}, value);
    

    or

    new int[] {1, 2, 4, 7}.Contains(value);
    
    0 讨论(0)
  • 2020-12-09 16:32
    if((new int[] {1, 2, 4, 7}).Contains(value))
    {
        // Do some work.
    }
    

    As others have pointed out, you could create an In() Extension method (I'll keep it generic so you can use it on any type):

    public static bool In<T>(T this obj, IEnumerable<T> col)
    {
        return col.Contains(obj);
    }
    

    So the initial example becomes:

    if(value.In(new int[] {1, 2, 4, 7}))
    {
        // Do some work.
    }
    
    0 讨论(0)
  • 2020-12-09 16:38
    using System;
    using System.Linq;
    
    static class SqlStyleExtensions
    {
        public static bool In(this string me, params string[] set)
        {
           return set.Contains(me);
        }
    }
    

    Usage:

    if (Variable.In("AC", "BC", "EA"))
    {
    
    } 
    
    0 讨论(0)
  • 2020-12-09 16:38

    I have made an extension method for this that I find quite useful. However, it is not much more than syntactic sugar wrapping the existing IEnumerable.Contains() function.

    /// <summary>
    /// Returns true if the value is represented in the provided enumeration.
    /// </summary>
    /// <typeparam name="T">Type of the value</typeparam>
    /// <param name="obj">The object to check if the enumeration contains</param>
    /// <param name="values">The enumeration that might contain the object</param>
    /// <returns>True if the object exists in the enumeration</returns>
    public static bool In<T>(this T obj, IEnumerable<T> values) {
        return values.Contains(obj);
    }
    

    Edit: Someone beat me to it, damnit. I'll keep by post here though since it's a more generic version.

    0 讨论(0)
  • 2020-12-09 16:38

    If you will do many lookups on the same dataset it is good from a performance perspective to use HashSet<T>.

    HashSet<int> numbers = new HashSet<int> { 1, 2, 4, 7 };
    bool is5inSet = numbers.Contains(5);
    
    0 讨论(0)
  • 2020-12-09 16:41

    Using LINQ

    var q = from x in collection
            where (new int[] { 1, 2, 4, 7}).Contains(x.value)
            select x
    
    0 讨论(0)
提交回复
热议问题