9

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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
loyalflow
  • 14,275
  • 27
  • 107
  • 168

5 Answers5

24

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

var str = String.Join(",", list.Select(x => x.Name));
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
6

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

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
4

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()));
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 2
    Starting with .net 4.0, There is string.Join(String, IEnumerable) and hence no need for ToArray() – DasKrümelmonster Mar 07 '13 at 21:30
  • can this also trim the string so there arent' any blank spaces? i should do a null check on the list before hand right? – loyalflow Mar 07 '13 at 21:40
  • @user1361315 most complete method of doing that would be `list.Where(x => x != null).Select(x => x.Name).Select(n => !String.IsNullOrEmpty(n))` -- though arguably less elegant. – p.s.w.g Mar 07 '13 at 21:43
  • Yes you can do `String.Join(",", list.Select(x => x.Name.Trim()));` and to check for nulls: `String.Join(",", list.Select(x => (x.Name != null) ? x.Name.Trim() : null));` (You can have null values in the sequence of strings you pass to `String.Join()`) – Matthew Watson Mar 07 '13 at 21:45
1

If performance is an issue, I wouldn't suggest this, but it is possible to use the Aggregate method of LINQ to do such a concatenation.

e.g.

using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Example> list = new List<Example>()
            {
                new Example() { Name = "John Doe" },
                new Example() { Name = "Jane Doe" },
                new Example() { Name = "Fred Doe" },
            };

            string s = list.Select(item => item.Name)
                           .Aggregate((accumulator, iterator) => accumulator += "," + iterator);
        }
    }

    public class Example
    {
        public string Name { get; set; }
    }
}

This could be useful, however, if your joining logic ends up being more complicated (a rare occurrence, I would suspect).

Kenneth K.
  • 2,987
  • 1
  • 23
  • 30
0

And one inelegant solution without Join

for(int x = 0; x < list.Count; x++)
{
    if (x > 0)
        sb.Append(",");

    sb.Append(list[x].Name);
}


var result = sb.toString();
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198