Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way of creating a comma separated list, and removing trailing comma [duplicate]

Tags:

c#

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);
like image 977
loyalflow Avatar asked Mar 07 '13 21:03

loyalflow


3 Answers

Use String.Join and Linq's IEnumerable.Select extension method.

var str = String.Join(",", list.Select(x => x.Name));
like image 123
p.s.w.g Avatar answered Nov 15 '22 00:11

p.s.w.g


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()));
like image 31
D Stanley Avatar answered Nov 14 '22 23:11

D Stanley


Description

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.

Sample

String.Join(",", list.Select(x => x.Name));

More Information

  • MSDN - String.Join Method (String, String[])
  • MSDN - Enumerable.Select
like image 23
dknaack Avatar answered Nov 15 '22 00:11

dknaack