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
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.
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();
}
Use string.Join:
string.Join(" ", something.Select(i => i.ToString()).ToArray())
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With