When I generate comma separated lists, I hate how I have to chop off the trailing comma.
Is there a better way? I do this fairly often so looking for opinions.
for(int x = 0; x < list.Count; x++)
{
sb.Append(list[x].Name);
sb.Append(",");
}
var result = sb.toString().Substring(0, result.length - 2);
Use String.Join and Linq's IEnumerable.Select extension method.
var str = String.Join(",", list.Select(x => x.Name));
Base case:
string.Join(",",list.Select(l => l.Name));
with null checks:
string.Join(",",list.Where(l => l != null).Select(l => l.Name));
with null/empty checks:
string.Join(",",list.Where(l => !string.IsNullOrEmpty(l)).Select(l => l.Name));
with trimming:
string.Join(",",list.Select(l => l.Name.Trim()));
with both:
string.Join(",",list.Where(l => !string.IsNullOrEmpty(l)).Select(l => l.Name.Trim()));
You can use the String.Join
and the Enumerable.Select
(namespace System.Linq) method
String.Join Concatenates all the elements of a string array, using the specified separator between each element.
Enumerable.Select Projects each element of a sequence into a new form.
String.Join(",", list.Select(x => x.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With