ICollection to String in good format in C #
I have a list:
List<int> list = new List<int> {1, 2, 3, 4, 5};
If you want a string representation of my list. But the list.ToString()
return code"System.Collections.Generic.List'1[System.Int32]"
I'm looking for a standard method:
string str = list.Aggregate("[",
(aggregate, value) =>
aggregate.Length == 1 ?
aggregate + value : aggregate + ", " + value,
aggregate => aggregate + "]");
and get "[1, 2, 3, 4, 5]"
Is there a standard .NET method for representing ICollection in a good string format?
+2
source to share
3 answers
Not that I know, but you can use an extension method like:
public static string ToString<T>(this IEnumerable<T> l, string separator)
{
return "[" + String.Join(separator, l.Select(i => i.ToString()).ToArray()) + "]";
}
Using:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.ToString(", "));
+7
source to share
If you have C # 3.0 and LINQ you can do this
var mystring = "[" + string.Join(", ", new List<int> {1, 2, 3, 4, 5}
.Select(i=>i.ToString()).ToArray()) + "]";
... here is an example of an extension method ...
public static string ToStrings<T>(this IEnumerable<T> input)
{
var sb = new StringBuilder();
sb.Append("[");
if (input.Count() > 0)
{
sb.Append(input.First());
foreach (var item in input.Skip(1))
{
sb.Append(", ");
sb.Append(item);
}
}
sb.Append("]");
return sb.ToString();
}
+1
source to share