most elegant way to return a string from List<int>

IMO, you were better off with your original version; LINQ is great, but it isn't the answer to every problem. In particular, the string.Join approach demands an extra array (for little gain), and the Aggregate approach uses lots of intermediate strings.

Perhaps make it an extension method, though - and lose the Format stuff:

public static string Concatenate<T>(this IEnumerable<T> source, string delimiter)
{
   var s= new StringBuilder();
   bool first = true;
   foreach(T t in source) {
      if(first) {
        first = false;
      } else {
        s.Append(delimiter);
      }
      s.Append(t);
   }    
   return s.ToString();
}

String result = String.Join(" ", list.Select(item => item.ToString()).ToArray());

If it's just a collection of type List<int> (and not List<int?>) there could only be 0's instead of NULLs.

But to address the hypothetical or more general null problem one could add a Where(item => item != null), use the conditional operator, or the null coalescing operator. But every "fix" added to the expression will make it less readable and elegant.


Use string.Join:

string.Join(" ", something.Select(i => i.ToString()).ToArray())

Tags:

C#