最优雅的方式返回从列表℃的字符串; INT> [英] most elegant way to return a string from List<int>
问题描述
什么是最优雅的方式从列表
返回一个字符串ok了,是的,我知道我可以做这样的事情。
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();
}
但是我相信有一种方法与lambda表达式
这样做我想也追加到一个StringBuilder但就是没有做什么预期
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
推荐答案
IMO,你和你的原始版本更好; LINQ是伟大的,但它不能解决所有问题。尤其是,的string.join
方法需要一个额外的数组(小增益),以及总结
方法使用< 。STRONG>许多中间串
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();
}
这篇关于最优雅的方式返回从列表℃的字符串; INT>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!