-1

I want to print an array via Console.writeline. I'm lazy and want to do it in one line, avoiding iterating through all the array.

Here is my code:

var costumers = new Costumers[10];

// Array initialization...

Console.WriteLine("Initial array: '{0}'",string.Join(Environment.NewLine,costumers.ToList()) );

Array.Sort(costumers);

Is it OK to use String.Join for this purpose or it decreases performance dramatically? Is there an elegant way to do it?

Thanks, Paul

Asieh hojatoleslami
  • 3,240
  • 7
  • 31
  • 45
Maria
  • 53
  • 4

1 Answers1

0

There is absolutely nothing wrong with using String.Join: the method is so straightforward that there is hardly anything that could go wrong implementing it. All you need is a StringBuilder, a single loop, and a bool flag to skip pre-pending the separator the first time around.

You could slightly improve your code by removing ToList() from the call, because Join accepts IEnumerable<T>:

Console.WriteLine("Initial array: '{0}'", string.Join<Costumer>(Environment.NewLine, costumers) );
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Unfortunately it does not compiles, when I pass the costumers array without the .ToList(), the compiler says its ambiguous invocation as String.Join can get(string, object[]) And String.Join(string, IEnumerable How can I solve this? Is there any param/flag I can give the compiler? Thanks – Maria Aug 16 '14 at 17:25
  • 1
    add the part with the `` or a direct cast – Random Dev Aug 16 '14 at 17:37