Transform an array into a string inline
What is the tersest way to transform an integer array into a string enumerating the elements inline? I'm thinking something like an anonymous function that performs the conversion.
var array = new int[] { 1, 2 }
var s = string.Format("{0}",
new []
{ /*inline transform array in开发者_运维百科to the string "1, 2"*/ });
Use string.Join
. In .NET 3.5 and earlier you need to convert to a string array first; in .NET 4 there's an overload taking IEnumerable<T>
. So depending on your version:
.NET 2.0 or 3.0 / C# 2:
string s = string.Join(", ",
Array.ConvertAll(delegate(int x) { return x.ToString(); });
.NET 2.0 or 3.0 / C# 3:
string s = string.Join(", ", Array.ConvertAll(x => x.ToString());
.NET 3.5 / C# 3:
string s = string.Join(", ", array.Select(x => x.ToString()).ToArray());
(or use the version which works with .NET 2.0 if you prefer).
.NET 4:
string s = string.Join(", ", array);
(I hadn't even seen that before today!)
With String.Join, for .NET 4.0:
var s = String.Join(", ",array);
This works because String.Join now has a overload that takes IEnumerable<T>,
For 3.5, you can use
var s = String.Join(", ", array.Select(n => n.ToString()).ToArray());
For previous .NET versions, see Jon Skeets more complete answer.
If you're on .Net 4:
var array = new int[] { 1, 2 };
var s = String.Join(", ", array);
There was a String.Join<T>(string, IEnumerable<T>)
overloaded added :)
ReSharper gives me something like:
public static string EnumerateToString(this int[] a, string separator)
{
return a.Aggregate("", (current, i) => current + i.ToString(separator));
}
精彩评论