C# 在一行中将对象列表转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14126421/
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
Convert list of objects to string in one line
提问by user1306322
I have a list of objects that implement ToString()
. I need to convert the whole list to one string in one line. How can I do that?
我有一个实现ToString()
. 我需要将整个列表转换为一行中的一个字符串。我怎样才能做到这一点?
采纳答案by eouw0o83hf
Another method that may help out is string.Join()
, which takes a set of objects and will join them with any delimiter you want. For instance:
另一种可能有帮助的方法是string.Join()
,它接受一组对象并将它们与您想要的任何分隔符连接起来。例如:
var combined = string.Join(", ", myObjects);
will make a string that is comma/space separated.
将创建一个以逗号/空格分隔的字符串。
回答by AaronLS
Assuming you mean your objects implement ToString, I believe this will do it:
假设你的意思是你的对象实现了 ToString,我相信这会做到:
String.Concat( objects.Select(o=>o.ToString()) );
As per dtb note, this should work as well:
根据 dtb 说明,这也应该有效:
String.Concat( objects );
See http://msdn.microsoft.com/en-us/library/dd991828.aspx
请参阅http://msdn.microsoft.com/en-us/library/dd991828.aspx
Of course, if you don't implement ToString, you can also do things like:
当然,如果你不实现 ToString,你也可以这样做:
String.Concat( objects.Select(o=>o.FirstName + " " + o.LastName) );
回答by Adil
You can use String.Jointo concatenate the object list.
您可以使用String.Join连接对象列表。
string str = String.Join(",", objects);
回答by Adam
None of these worked for me. I'm confused, because the docs explicitly say they won't work (require string, not object). But modifying @Adil's original answer (found by looking at the previous revisions), I got a version that works fine:
这些都不适合我。我很困惑,因为文档明确表示它们不起作用(需要字符串,而不是对象)。但是修改@Adil 的原始答案(通过查看以前的修订版找到),我得到了一个可以正常工作的版本:
string.Join( ",", objectList.Select(c=>c.ToString()).ToArray<string>())
EDIT: as per @Chris's comment - I'm using Unity's version of .NET. I used the Microsoft docs as reference, so I'm still confused why this got downvoted, but ... maybe it's a Unity-specific problem that needs this solution.
编辑:根据@Chris 的评论 - 我正在使用 Unity 的 .NET 版本。我使用 Microsoft 文档作为参考,所以我仍然很困惑为什么这会被否决,但是......也许这是一个需要这个解决方案的 Unity 特定问题。