How to join int[] to a character separated string in .NET?

后端 未结 11 814
广开言路
广开言路 2020-11-29 19:17

I have an array of integers:

int[] number = new int[] { 2,3,6,7 };

What is the easiest way of converting these into a single string where

相关标签:
11条回答
  • 2020-11-29 19:54

    forget about .net 3.5 and use next code in .net core

    var result = string.Join(",", ints);
    
    0 讨论(0)
  • 2020-11-29 19:59
    var ints = new int[] {1, 2, 3, 4, 5};
    var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
    Console.WriteLine(result); // prints "1,2,3,4,5"
    

    EDIT: As of (at least) .NET 4.5,

    var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
    

    is equivalent to:

    var result = string.Join(",", ints);
    

    EDIT:

    I see several solutions advertise usage of StringBuilder. Someone complaints that Join method should take an IEnumerable argument.

    I'm going to disappoint you :) String.Join requires array for a single reason - performance. Join method needs to know the size of the data to effectively preallocate necessary amount of memory.

    Here is a part of internal implementation of String.Join method:

    // length computed from length of items in input array and length of separator
    string str = FastAllocateString(length);
    fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
    {
        UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
        buffer.AppendString(value[startIndex]);
        for (int j = startIndex + 1; j <= num2; j++)
        {
            buffer.AppendString(separator);
            buffer.AppendString(value[j]);
        }
    }
    

    I'm too lazy to compare performance of suggested methods. But something tells me that Join will win :)

    0 讨论(0)
  • 2020-11-29 19:59

    One mixture of the two approaches would be to write an extension method on IEnumerable<T> which used a StringBuilder. Here's an example, with different overloads depending on whether you want to specify the transformation or just rely on plain ToString. I've named the method "JoinStrings" instead of "Join" to avoid confusion with the other type of Join. Perhaps someone can come up with a better name :)

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    public static class Extensions
    {
        public static string JoinStrings<T>(this IEnumerable<T> source, 
                                            Func<T, string> projection, string separator)
        {
            StringBuilder builder = new StringBuilder();
            bool first = true;
            foreach (T element in source)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    builder.Append(separator);
                }
                builder.Append(projection(element));
            }
            return builder.ToString();
        }
    
        public static string JoinStrings<T>(this IEnumerable<T> source, string separator)
        {
            return JoinStrings(source, t => t.ToString(), separator);
        }
    }
    
    class Test
    {
    
        public static void Main()
        {
            int[] x = {1, 2, 3, 4, 5, 10, 11};
    
            Console.WriteLine(x.JoinStrings(";"));
            Console.WriteLine(x.JoinStrings(i => i.ToString("X"), ","));
        }
    }
    
    0 讨论(0)
  • 2020-11-29 20:01

    If your array of integers may be large, you'll get better performance using a StringBuilder. E.g.:

    StringBuilder builder = new StringBuilder();
    char separator = ',';
    foreach(int value in integerArray)
    {
        if (builder.Length > 0) builder.Append(separator);
        builder.Append(value);
    }
    string result = builder.ToString();
    

    Edit: When I posted this I was under the mistaken impression that "StringBuilder.Append(int value)" internally managed to append the string representation of the integer value without creating a string object. This is wrong: inspecting the method with Reflector shows that it simply appends value.ToString().

    Therefore the only potential performance difference is that this technique avoids one array creation, and frees the strings for garbage collection slightly sooner. In practice this won't make any measurable difference, so I've upvoted this better solution.

    0 讨论(0)
  • 2020-11-29 20:05

    In .NET 4.0, string join has an overload for params object[], so it's as simple as:

    int[] ids = new int[] { 1, 2, 3 };
    string.Join(",", ids);
    

    example

    int[] ids = new int[] { 1, 2, 3 };
    System.Data.Common.DbCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM some_table WHERE id_column IN (@bla)");
    cmd.CommandText = cmd.CommandText.Replace("@bla",  string.Join(",", ids));
    

    In .NET 2.0, it's a tiny little bit more difficult, since there's no such overload. So you need your own generic method:

    public static string JoinArray<T>(string separator, T[] inputTypeArray)
    {
        string strRetValue = null;
        System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
    
        for (int i = 0; i < inputTypeArray.Length; ++i)
        {
            string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
    
            if (!string.IsNullOrEmpty(str))
            { 
                // SQL-Escape
                // if (typeof(T) == typeof(string))
                //    str = str.Replace("'", "''");
    
                ls.Add(str);
            } // End if (!string.IsNullOrEmpty(str))
    
        } // Next i 
    
        strRetValue= string.Join(separator, ls.ToArray());
        ls.Clear();
        ls = null;
    
        return strRetValue;
    }
    

    In .NET 3.5, you can use extension methods:

    public static class ArrayEx
    {
    
        public static string JoinArray<T>(this T[] inputTypeArray, string separator)
        {
            string strRetValue = null;
            System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
    
            for (int i = 0; i < inputTypeArray.Length; ++i)
            {
                string str = System.Convert.ToString(inputTypeArray[i], System.Globalization.CultureInfo.InvariantCulture);
    
                if (!string.IsNullOrEmpty(str))
                { 
                    // SQL-Escape
                    // if (typeof(T) == typeof(string))
                    //    str = str.Replace("'", "''");
    
                    ls.Add(str);
                } // End if (!string.IsNullOrEmpty(str))
    
            } // Next i 
    
            strRetValue= string.Join(separator, ls.ToArray());
            ls.Clear();
            ls = null;
    
            return strRetValue;
        }
    
    }
    

    So you can use the JoinArray extension-method.

    int[] ids = new int[] { 1, 2, 3 };
    string strIdList = ids.JoinArray(",");
    

    You can also use that extension method in .NET 2.0, if you add the ExtensionAttribute to your code:

    // you need this once (only), and it must be in this namespace
    namespace System.Runtime.CompilerServices
    {
        [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
        public sealed class ExtensionAttribute : Attribute {}
    }
    
    0 讨论(0)
提交回复
热议问题