What is the linq equivalent to the SQL IN operator

前端 未结 9 2017
梦如初夏
梦如初夏 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:55

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

        public static bool In(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.

提交回复
热议问题