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

前端 未结 8 2238
死守一世寂寞
死守一世寂寞 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:35

    You can do this more efficiently using the following extension method:

        ///Appends a list of strings to a StringBuilder, separated by a separator string.
        ///The StringBuilder to append to.
        ///The strings to append.
        ///A string to append between the strings.
        public static StringBuilder AppendJoin(this StringBuilder builder, IEnumerable 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;
        }
    
        ///Combines a collection of strings into a single string.
        public static string Join(this IEnumerable strings, string separator, Func selector) { return strings.Select(selector).Join(separator); }
        ///Combines a collection of strings into a single string.
        public static string Join(this IEnumerable strings, string separator) { return new StringBuilder().AppendJoin(strings, separator).ToString(); }
    

提交回复
热议问题