C# 对象列表上的 String.Join
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10540584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String.Join on a List of Objects
提问by user17753
In C#, if I have a List<MyObj>where MyObjis a custom class with an overridden ToString()method such that each MyObjobject in the List can be easily converted to a string.
在 C# 中,如果我有一个List<MyObj>whereMyObj是一个带有重写ToString()方法的自定义类,这样MyObj列表中的每个对象都可以轻松转换为字符串。
How can I jointhis List<MyObj>with a delimiter, such as for example a pipe (|) into a single string.
我怎样才能加入这个List<MyObj>有一个分隔符,例如管道(|)合并为一个字符串。
So, if I had 3 MyObj objects whose ToString methods would produce AAA, BBB, CCC respectively. I would create a single string: AAA|BBB|CCC.
所以,如果我有 3 个 MyObj 对象,它们的 ToString 方法将分别产生 AAA、BBB、CCC。我会创建一个字符串:AAA|BBB|CCC。
For a list of a simpler type, such as List<string>I perform this simply as: String.Join("|",myList.ToArray());. Is there a way I can do something similar to that? Or am I forced to iterate over the Object List and use a String Builder to append each object's ToString in the list together?
对于简单类型的列表,比如List<string>我执行这项简称为:String.Join("|",myList.ToArray());。有没有办法我可以做类似的事情?或者我是否被迫遍历对象列表并使用字符串生成器将每个对象的 ToString 附加到列表中?
采纳答案by Jon Skeet
In .NET 4, you could just use:
在 .NET 4 中,你可以使用:
var x = string.Join("|", myList);
.NET 3.5 doesn't have as many overloads for string.Jointhough - you need to perform the string conversion and turn it into an array explicitly:
.NET 3.5 虽然没有那么多重载string.Join- 您需要执行字符串转换并将其显式转换为数组:
var x = string.Join("|", myList.Select(x => x.ToString()).ToArray());
Compare the overloads available:
比较可用的重载:

