1

This rather inelegant method takes an input array of objects and outputs a string result, which is the result of ToString() for each element, space separated.

string Format(object[] args)
{
   var res = string.Empty;
   foreach (var o in args)
   {
      res += o.ToString();
      if (o != args.Last())
         res += " ";
   }
}

Surely there is a C# method hidden somewhere to do this type of operation, or if not, a more elegant way to write it using Linq? Another concern with how I have written this method is the garbage generation by building the string incrementally.

James
  • 1,973
  • 1
  • 18
  • 32
  • 19
    You've just recreated `string.Join` – McGarnagle Jul 25 '13 at 20:41
  • What @McGarnagle said, plus it's going to fall over if `o` is null. – Moo-Juice Jul 25 '13 at 20:42
  • Rename your method to Join2 – Sriram Sakthivel Jul 25 '13 at 20:43
  • 1
    What @Moo-Juice said, plus if you pass in value types they all get boxed & if there are a lot of objects you'd be better of using a `StringBuilder`. Plus Format is a bad name as you're not actually doing any formatting... – Trevor Pilley Jul 25 '13 at 20:43
  • Remember it a object so I think o[0].ToString() would give you the string object. – Bit Jul 25 '13 at 20:45
  • No I should have type (((object[])(o))[0]).ToString() – Bit Jul 25 '13 at 20:48
  • 1
    Looking at the implementation of String.Join, it meets all the requirements: uses stringbuilder to avoid garbage, calls ToString on each element for me, and is more elegant than even linq since it is a single static method call. This is a different accepted answer than the proposed duplicate question. – James Jul 25 '13 at 21:07
  • @James `String.Join` is the highest up voted answer on that possible dupe. – Steven Jeuris Jul 25 '13 at 22:28
  • Edited my question so that it is not specifically about "how to do this with Linq" but how to do this operation more 'elegantly'. Since string.Join is definitely more elegent and deals with the garbage generation issue, I would hope that future people see this question and its accepted answer rather than the other proposed duplicate. – James Jul 26 '13 at 22:03

3 Answers3

12
var res = String.Join(" ", args);
I4V
  • 34,891
  • 6
  • 67
  • 79
3
var res = String.Join(" ", args.Select(x=> x != null ? x.ToString() : ""));

Will join together a string representation of each item.

1

You can use the aggregate method which I tend to prefer.

args.Where(x => x != null).Aggregate((c, n) => c.ToString() + " " + n.ToString());
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • @I4V well obv you get a null reference exception on index 2. `args.Where(x => x != null).Aggregate( ... )` easily solves that problem though. – evanmcdonnal Jul 25 '13 at 21:07