转换整数数组以在SQL“IN”子句中使用

时间:2009-11-13 15:54:17

标签: c# sql arrays

当然有一个框架方法给出一个整数数组,字符串等将它们转换成一个可以在SQL“IN”子句中使用的列表?

e.g。

int[] values = {1,2,3};

会去

"(1,2,3)"

8 个答案:

答案 0 :(得分:17)

var inClause = "("
     + String.Join(",", values.Select(x => x.ToString()).ToArray()) 
     + ")";

注意:您不再需要在.NET Framework 4中调用.ToArray()。添加了新的String.Join<T>(string separator, IEnumerable<string> values)方法。

答案 1 :(得分:5)

如果您无权访问.NET 3.5扩展方法,则可以执行以下操作:

StringBuilder sb = new StringBuilder();
sb.Append('(');

foreach (int i in values) {
    sb.Append(i).Append(',');
}

// remove final ,
sb.Length -= 1;
sb.Append(')');

string inValue = sb.ToString();

哪个适用于.NET 2

答案 2 :(得分:5)

您可以使用String.Join方法,如下所示:

var str = "(" + string.Join(", ", Array.ConvertAll(values, v => v.ToString(CultureInfo.InvariantCulture)));

假设values是一个数组,Array.ConvertAll应该比ToArray的LINQ更有效。

答案 3 :(得分:2)

这也可以在一行中完成

public string ToInStatement(this int[] values) {
    string[] stringValues = 
       Array.ConvertAll<int, string>(values, Convert.ToString);
    string result = "(" + String.Join(",", stringValues) + ")";
    return result;
 }

答案 4 :(得分:1)

如果整数列表很大,最终可能会生成一个太长而且数据库无法接受的字符串。例如。我认为SQL2000中VARCHAR的最大长度大约是8K。

所以我有一组辅助方法,类似于下面的示例,它返回一个字符串的枚举,然后可以按如下方式使用:

List<int> idList = ...;
using(SqlCommand command = ...)
{
    ...
    foreach(string idString in ConcatenateValues(ids,",", maxLength, false))
    {
       command.Parameters[...] = idString;
       // or command.CommandText = "SELECT ... IN (" + idString + ")...";
       ... execute command ...
    }
}

concatenate方法可能如下所示:

public static IEnumerable<string> ConcatenateValues(IEnumerable<int> values, string separator, int maxLength, bool skipDuplicates)
{
    IDictionary<int, string> valueDictionary = null;
    StringBuilder sb = new StringBuilder();
    if (skipDuplicates)
    {
        valueDictionary = new Dictionary<int, string>();
    }
    foreach (int value in values)
    {
        if (skipDuplicates)
        {
            if (valueDictionary.ContainsKey(value)) continue;
            valueDictionary.Add(value, "");
        }
        string s = value.ToString(CultureInfo.InvariantCulture);
        if ((sb.Length + separator.Length + s.Length) > maxLength)
        {
            // Max length reached, yield the result and start again
            if (sb.Length > 0) yield return sb.ToString();
            sb.Length = 0;
        }
        if (sb.Length > 0) sb.Append(separator);
        sb.Append(s);
    }
    // Yield whatever's left over
    if (sb.Length > 0) yield return sb.ToString();
}

答案 5 :(得分:0)

嘿,很棒的建议,只是稍作修改

public static class IEnumerableExtensions
{
    // reasonable to assume you will use this everywhere, not just
    // Sql statements, but log statements, anywhere you need to 
    // dump a list into a readable format!
    // 
    // HINT: extra credit: you can generalize this, and provide
    // specialized short hands that invoke the general method
    public static string ToCommaSeparatedString<T>(this IEnumerable<T> values)
    {
         // SIGH: so apparently this does not generate minimal
         // assembler on every machine, please note the following
         // is written for clarity, please feel free to substitute
         // your own favourite ultra-performance high-octance
         // string appender algorithm
         StringBuilder commaSeparated = new StringBuilder ();
         foreach (T value in values)
         {
             // PERF: store format string as const
             commaSeparated.AppendFormat ("{0}, ", value);
         }
         // PERF: store trim chars as static readonly array
         return commaSeparated.Trim (", ".ToCharArray ());
    }
}

...
// elsewhere in code
List<int> myIdentifiers = new List<int> { 1, 2, 3, 4, 5, };
string mySqlIdentifierList = myIdentifiers.ToCommaSeparatedList ();
string mySqlStatementFormat = "SELECT * FROM [SomeTable] WHERE [Id] IN ({0})";
string mySqlStatement = 
    string.format (mySqlStatementFormat, mySqlIdentifierList);
...

答案 6 :(得分:0)

您可以使用以下扩展方法更有效地执行此操作:

    ///<summary>Appends a list of strings to a StringBuilder, separated by a separator string.</summary>
    ///<param name="builder">The StringBuilder to append to.</param>
    ///<param name="strings">The strings to append.</param>
    ///<param name="separator">A string to append between the strings.</param>
    public static StringBuilder AppendJoin(this StringBuilder builder, IEnumerable<string> strings, string separator) {
        if (builder == null) throw new ArgumentNullException("builder");
        if (strings == null) throw new ArgumentNullException("strings");
        if (separator == null) throw new ArgumentNullException("separator");

        bool first = true;

        foreach (var str in strings) {
            if (first)
                first = false;
            else
                builder.Append(separator);

            builder.Append(str);
        }

        return builder;
    }

    ///<summary>Combines a collection of strings into a single string.</summary>
    public static string Join<T>(this IEnumerable<T> strings, string separator, Func<T, string> selector) { return strings.Select(selector).Join(separator); }
    ///<summary>Combines a collection of strings into a single string.</summary>
    public static string Join(this IEnumerable<string> strings, string separator) { return new StringBuilder().AppendJoin(strings, separator).ToString(); }

答案 7 :(得分:0)

/// <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())), ")");
}