Any elegant ways of converting a IList collection to a string of comma separated id's?
"1,234,2,324,324,2"
Any elegant ways of converting a IList collection to a string of comma separated id's?
"1,234,2,324,324,2"
IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
Console.WriteLine(string.Join(",", list));
ToArray
. The string.Join
overload used operates on IEnumerable<string>
. –
Colene Select
either, you can just pass in an IEnumerable<T>
(in this case, of ints) and it'll get the string value of each one for you. (That overload was also added at the same time.) –
Excommunicate You can do:
// Given: IList<int> collection;
string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
This will do it
IList<int> strings = new List<int>(new int[] { 1,2,3,4 });
string[] myStrings = strings.Select(s => s.ToString()).ToArray();
string joined = string.Join(",", myStrings);
OR entirely with Linq
string aggr = strings.Select(s=> s.ToString()).Aggregate((agg, item) => agg + "," + item);
// list = IList<MyObject>
var strBuilder = new System.Text.StringBuilder();
foreach(var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
strBuilder = strBuilder.SubString(0, strBuilder.Length -1);
return strBuilder.ToString();
List<int> intList = new List<int>{1,234,2,324,324,2};
var str = intList.Select(i => i.ToString()).Aggregate( (i1,i2) => string.Format("{0},{1}",i1,i2));
Console.WriteLine(str);
mstrickland has a good idea on using string builder because of its speed with larger lists. However, you can't set a stringbuilder as a string. Try this instead.
var strBuilder = new StringBuilder();
foreach (var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
return strBuilder.ToString(0, strBuilder.Length - 1);
© 2022 - 2024 — McMap. All rights reserved.