having a List<int> of integers (for example: 1 - 3 - 4)
how can I convert it in a string of this type?
For example, the output should be:
string values = "1,3,4";
var ints = new List<int>{1,3,4};
var stringsArray = ints.Select(i=>i.ToString()).ToArray();
var values = string.Join(",", stringsArray);
String.Join has an overload taking an IEnumerable<T> so this can be done without the intermediate array (this overload calls ToString() on each input element): string.Join(",", ints).String.Split().Another solution would be the use of Aggregate. This is known to be much slower then the other provided solutions!
var ints = new List<int>{1,2,3,4};
var strings =
ints.Select(i => i.ToString(CultureInfo.InvariantCulture))
.Aggregate((s1, s2) => s1 + ", " + s2);
See comments below why you should not use it. Use String.Join or a StringBuilder instead.
public static string ToCommaString(this List<int> list)
{
if (list.Count <= 0)
return ("");
if (list.Count == 1)
return (list[0].ToString());
System.Text.StringBuilder sb = new System.Text.StringBuilder(list[0].ToString());
for (int x = 1; x < list.Count; x++)
sb.Append("," + list[x].ToString());
return (sb.ToString());
}
public static List<int> CommaStringToIntList(this string _s)
{
string[] ss = _s.Split(',');
List<int> list = new List<int>();
foreach (string s in ss)
list.Add(Int32.Parse(s));
return (list);
}
Usage:
String s = "1,2,3,4";
List<int> list = s.CommaStringToIntList();
list.Add(5);
s = list.ToCommaString();
s += ",6";
list = s.CommaStringToIntList();
Use the Stringify.Library nuget package
Example 1 (Default delimiter is implicitly taken as comma)
string values = "1,3,4";
var output = new StringConverter().ConvertFrom<List<int>>(values);
Example 2 (Specifying the delimiter explicitly)
string values = "1 ; 3; 4";
var output = new StringConverter().ConvertFrom<List<int>>(values), new ConverterOptions { Delimiter = ';' });