What is the linq equivalent to the SQL IN operator

前端 未结 9 2011
梦如初夏
梦如初夏 2020-12-05 06:34

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:

WHERE ID IN (2,3,4,5)

How can I

相关标签:
9条回答
  • 2020-12-05 06:41

    An IEnumerable<T>.Contains(T) statement should do what you're looking for.

    0 讨论(0)
  • 2020-12-05 06:44

    Perform the equivalent of an SQL IN with IEnumerable.Contains().

    var idlist = new int[] { 2, 3, 4, 5 };
    
    var result = from x in source
              where idlist.Contains(x.Id)
              select x;
    
    0 讨论(0)
  • 2020-12-05 06:52

    A very basic example using .Contains()

    List<int> list = new List<int>();
    for (int k = 1; k < 10; k++)
    {
        list.Add(k);
    }
    
    int[] conditionList = new int[]{2,3,4};
    
    var a = (from test in list
             where conditionList.Contains(test)
             select test);
    
    0 讨论(0)
  • 2020-12-05 06:55
    db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));
    

    or

    from x in db.SomeTable
    where new[] {2,3,4,5}.Contains(x)
    
    0 讨论(0)
  • 2020-12-05 06:55

    Following is a generic extension method that can be used to search a value within a list of values:

        public static bool In<T>(this T searchValue, params T[] valuesToSearch)
        {
            if (valuesToSearch == null)
                return false;
            for (int i = 0; i < valuesToSearch.Length; i++)
                if (searchValue.Equals(valuesToSearch[i]))
                    return true;
    
            return false;
        }
    

    This can be used as:

    int i = 5;
    i.In(45, 44, 5, 234); // Returns true
    
    string s = "test";
    s.In("aa", "b", "c"); // Returns false
    

    This is handy in conditional statements.

    0 讨论(0)
  • 2020-12-05 06:59

    Intersect and Except are a little more concise and will probably be a bit faster too.

    IN

    collection.Intersect(new[] {2,3,4,5});
    

    NOT IN

    collection.Except(new[] {2,3,4,5});
    

    or

    Method syntax for IN

    collection.Where(x => new[] {2,3,4,5}.Contains(x));
    

    and NOT IN

    collection.Where(x => !(new[] {2,3,4,5}.Contains(x)));
    
    0 讨论(0)
提交回复
热议问题