9

Lets say I have an array (or list) of items

A[] = [a,b,c,d,e]

If I want to print them out so each item is separated by a comma (or any other delimiter), I generally have to do this:

for(int i=0; i < A.Count; i++)
{
    Console.Write(A[i]);

    if (i != A.Count-1)
        Console.Write(",");
}

So, my output looks like:

a,b,c,d,e

Is there a better or neater way to achieve this?

I like to use a foreach loop, but that prints a comma after the last element as well, which is undesirable.

Ayush
  • 41,754
  • 51
  • 164
  • 239

7 Answers7

28
Console.WriteLine(string.Join(",", A));
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • String is a class. string is a datatype. string.Join doesn't make sense symantically it should be String.Join – Muhammad Hasan Khan Oct 07 '11 at 02:58
  • 6
    @HasanKhan There is [no difference](http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-s-the-difference-between-code-string-code-and-code-system-string-code.aspx) between `string` and `System.String`. It's a developer preference. – vcsjones Oct 07 '11 at 03:04
  • 1
    @vcsjones DUh! I know its an alias. The difference is in semantics and code readability. Methods on data type doesn't make sense. – Muhammad Hasan Khan Oct 07 '11 at 03:07
  • ooh, nice! I wasn't aware of this. one question though: how could I use this if I had an array of object A where A has an int and a string data member? So, I want to do this on `A[i].string`? – Ayush Oct 07 '11 at 03:24
  • 5
    @HasanKhan A class *is* a data type: `string` and `System.String` both refer to the same class, but the former is also a C# keyword. I agree with vscjones, using one or the other comes down to developer preference. Personally, I find `string.Join` more readable than the alternative as I never use `String`. – Bojan Resnik Oct 07 '11 at 03:26
  • 1
    @xbonez you can do `string.Join(",", arrayOfAs.Select(a => a.StringMember))` – Bala R Oct 07 '11 at 03:26
  • @BojanResnik http://stackoverflow.com/questions/7074/in-c-what-is-the-difference-between-string-and-string – Muhammad Hasan Khan Oct 07 '11 at 05:57
9

You are looking for String.Join():

var list = String.join(",", A);

String.Join Method (String, String[])

 Concatenates all the elements of a string array, using the specified separator between each element.

public static string Join(
    string separator,
    params string[] value
)
NullUserException
  • 83,810
  • 28
  • 209
  • 234
6

Is there a better or neater way to achieve this? I like to use a foreach loop, but that prints a comma after the last element as well, which is undesirable.

As others have said, Join does the right thing. But here's another way to think about the problem that might help you in the future. Instead of thinking of the problem as put a comma after every element except the last element -- which you correctly note makes it difficult to work with the "foreach" loop -- think of the problem as put a comma before every element except the first element. Now it is easy to do with a foreach loop!

For about a million more ways to solve a similar problem see:

Eric Lippert's challenge "comma-quibbling", best answer?

And the original blog post:

http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx

Community
  • 1
  • 1
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • I have actually considered it as a 'put a comma before every element but the first one' and still been unable to solve it with a foreach. Maybe I'm missing something obvious. Looking into your links now for, hopefully, a better understanding. Thanks for the links. – Ayush Oct 10 '11 at 07:09
  • 1
    @xbonez : "Put a comma before every element but the first one" is done by using a conditional on a `bool` that is changed within the loop. For example, `if (!isFirstElement){sb.Append(",");}isFirstElement=false;` – Brian Oct 10 '11 at 13:32
4

Use the string.Join method, very handy.

String.Join(",", my_array)
Gishu
  • 134,492
  • 47
  • 225
  • 308
3

Use:

String.Join(",", arrayOfStrings);

Anas Karkoukli
  • 1,342
  • 8
  • 13
2
string separator = String.Empty;
for(int i=0; i < A.Length; i++)
{
    Console.Write(seperator);
    Console.Write(A[i]);
    separator = ",";
}
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
  • 1
    Why the downvote? This appears to be a sensible solution. (Though "separator" is misspelled.) – Eric Lippert Oct 07 '11 at 15:30
  • I'm definitely +1ing this one. This is what I do most of the time to solve this kind of problem, though I usually use a StringBuilder and foreach – Fede Oct 07 '11 at 15:54
  • Eric, do you actually like this solution? I feel that setting separator in every iteration makes the code very difficult to read. [And no, I didn't down vote but I won't up vote this answer either.] – SolutionYogi Oct 07 '11 at 16:00
1
using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string[] values = new string[]{"banana", "papaya", "melon"};

        var result = values.Aggregate((x,y) => x + ", " + y);

        Console.WriteLine(result);
    }
}
MEC
  • 1,690
  • 1
  • 17
  • 23