C# List<string> to string with delimiter

北城余情 提交于 2019-11-26 03:02:16

问题


Is there a function in C# to quickly convert some collection to string and separate values with delimiter?

For example:

List<string> names --> string names_together = \"John, Anna, Monica\"


回答1:


You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.




回答2:


You can also do this with linq if you'd like

var names = new List<string>() { "John", "Anna", "Monica" };
var joinedNames = names.Aggregate((a, b) => a + ", " + b);

Although I prefer the non-linq syntax in Quartermeister's answer and I think Aggregate might perform slower (probably more string concatenation operations).



来源:https://stackoverflow.com/questions/3575029/c-sharp-liststring-to-string-with-delimiter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!