Convert an array of integers for use in a SQL “IN” clause

前端 未结 8 2176
死守一世寂寞
死守一世寂寞 2021-01-05 03:44

Surely there is a framework method that given an array of integers, strings etc converts them into a list that can be used in a SQL \"IN\" clause?

e.g.

相关标签:
8条回答
  • 2021-01-05 04:36
    /// <summary>
    /// Converts an array of integers into a string that may be used in a SQL IN expression.
    /// </summary>
    /// <param name="values">The array to convert.</param>
    /// <returns>A string representing the array as a parenthetical comma-delemited list. If the array
    /// is empty or missing, then "(null)" is returned.</returns>
    public static string ToSqlInList(int[] values)
    {
        if (values == null || values.Length == 0)
            return "(null)";  // In SQL the expression "IN (NULL)" is always false.
    
        return string.Concat("(", string.Join(",", Array.ConvertAll<int, string>(values,x=>x.ToString())), ")");
    }
    
    0 讨论(0)
  • 2021-01-05 04:38

    This could be done in one line too

    public string ToInStatement(this int[] values) {
        string[] stringValues = 
           Array.ConvertAll<int, string>(values, Convert.ToString);
        string result = "(" + String.Join(",", stringValues) + ")";
        return result;
     }
    
    0 讨论(0)
提交回复
热议问题