开发者

Convert array of integers to comma-separated string

It's a simple question; I am a newbie in C#, how can I perform the following

  • I want to convert an array of integers to a comma-separated string.

I have

int[] arr = new int[5] {1,2,3,4,5};

I want to convert it to one string

s开发者_运维百科tring => "1,2,3,4,5"


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

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);


.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))


int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);


You can have a pair of extension methods to make this task easier:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();


Use LINQ Aggregate method to convert array of integers to a comma separated string

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

output will be

1,2,3,4

This is one of the solution you can use if you have not .net 4 installed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜