ICollection à cordes dans un bon format en C #
-
21-09-2019 - |
Question
J'ai une liste:
List<int> list = new List<int> {1, 2, 3, 4, 5};
Si vous voulez obtenir la présentation de la chaîne de ma liste. Mais le code list.ToString()
"System.Collections.Generic.List'1[System.Int32]"
retour
Je cherche méthode standard comme ceci:
string str = list.Aggregate("[",
(aggregate, value) =>
aggregate.Length == 1 ?
aggregate + value : aggregate + ", " + value,
aggregate => aggregate + "]");
et obtenir "[1, 2, 3, 4, 5]"
Y at-il .NET méthode standard pour ICollection de présentation en bon format de chaîne?
La solution
Non pas que je suis au courant, mais vous pouvez faire une méthode d'extension comme suit:
public static string ToString<T>(this IEnumerable<T> l, string separator)
{
return "[" + String.Join(separator, l.Select(i => i.ToString()).ToArray()) + "]";
}
Avec l'utilisation suivante:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine(list.ToString(", "));
Autres conseils
Vous pouvez utiliser string.join comme
"[" + string.Join(", ", list.ConvertAll(i => i.ToString()).ToArray()) +"]";
Si vous avez C # 3.0 et LINQ, vous pouvez le faire
var mystring = "[" + string.Join(", ", new List<int> {1, 2, 3, 4, 5}
.Select(i=>i.ToString()).ToArray()) + "]";
... voici une méthode d'extension exemple ...
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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow