获取逗号分隔列表For Loop或String.Join()。哪个最好? [英] To get a comma separated list For Loop or String.Join().Which is Best?
本文介绍了获取逗号分隔列表For Loop或String.Join()。哪个最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨朋友们,
我想得到一个以逗号分隔的列表。我有两种方法。
第一个是正常的For循环,第二个是String.Join()方法。
考虑性能是最好的方法。
Hi Friends,
I would like to get a comma separated list. I have two approaches.
First one is normal For loop and second one is String.Join() Method.
Considering the performance which will be the best approach.
StringBuilder KeyTmsList = new StringBuilder();
for (int i = 0; i < dsKeytms.Tables[0].Rows.Count; i++)
{
KeyTmsList = KeyTmsList.Append("'" + dsKeytms.Tables[0].Rows[i]["KEY_TMS"].ToString() + "'" + ",");
}
KeyTmsList = KeyTmsList.Remove(KeyTmsList.Length - 1, 1);
string KeyTmsList = string.Join(",", dsKeytms.Tables[0].AsEnumerable().Select(r => r.Field<string>("KEY_TMS")).ToArray());
推荐答案
我认为string.join()是最好的选择。
I think string.join() is the best option.
比较'StringBuilder和'Join这里很难,因为你使用不同的方法将你的Tables [0](它的Rows)的内容组合成一个可枚举的形式来进行操作:在第二个例子中,你使用的是Linq而不是for -loop。
因此,在某种程度上,你真的要问使用Linq进行比较,使用'for-loop。
有关于在这里使用'Join vs.'StringBuilder的详细讨论:[ ^ ]你可能觉得有用。
另见这里的讨论和时间结果:[ ^ ]。
我对上述讨论的阅读表明,'Join和'StringBuilder的表现同样相称,但我相信对于你的情况,你需要做一些时间。
仅在这些条件下,内部加入使用StringBuilder的特殊情况才真实:
1. .NET 4.0或之后
2.加入的参数是IEnumerable< string>
但是,当Join是一个数组的参数,Join使用FastAllocateS tring()和UnSafeCharBuffer)......请参阅上面的第二个链接,了解此评论的来源。
A comparison of 'StringBuilder and 'Join is difficult here because you are using different methods of "composing" the contents of your Tables[0] (its Rows) into an enumerable form for manipulation: in the second example you are using Linq instead of a for-loop.
So, in some ways you are really asking about comparing using Linq to using a 'for-loop.
There is a detailed discussion of using 'Join vs. 'StringBuilder here: [^] which you might find useful.
Also see the discussion and timing results here: [^].
My reading of the above discussions suggests that 'Join and 'StringBuilder are about equally performant, but I believe that for your case you'd have to do some timing.
The special case of 'Join using 'StringBuilder internally appears to be true only under these conditions:
1. .NET 4.0 or later
2. the argument to 'Join is an IEnumerable<string>
However, when the arguments to 'Join is an Array, 'Join uses "FastAllocateString() and UnSafeCharBuffer)" ... see the second link above for the source of this comment.
这篇关于获取逗号分隔列表For Loop或String.Join()。哪个最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文