Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

What is the most elegant way to return a string from a List ok, yeah, I know I can do something like

public string Convert(List<int> something)
{
    var s = new StringBuilder();
    foreach(int i in something)
        s.AppendFormat("{0} ", i);

    return s.ToString();
}

but i m sure there is a way to do this with lambdas I tried also to append to a stringbuilder but that is not doing whats expected

like image 494
roundcrisis Avatar asked Aug 26 '09 11:08

roundcrisis


4 Answers

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.

like image 117
Daniel Brückner Avatar answered Oct 27 '22 07:10

Daniel Brückner


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();
}
like image 26
Marc Gravell Avatar answered Oct 27 '22 09:10

Marc Gravell


Use string.Join:

string.Join(" ", something.Select(i => i.ToString()).ToArray())
like image 12
Chris Shaffer Avatar answered Oct 27 '22 08:10

Chris Shaffer


Use string.Join:

List<int> data = ..;
var result = string.Join(";", data); // (.NET 4.0 only)
var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); // (.NET 3.5)
like image 7
Stephen Cleary Avatar answered Oct 27 '22 09:10

Stephen Cleary