将通用列表转换为 CSV 字符串 [英] Converting a generic list to a CSV string
问题描述
我有一个整数值列表 (List),想生成一串逗号分隔的值.即列表中的所有项目输出到单个逗号分隔列表.
I have a list of integer values (List) and would like to generate a string of comma delimited values. That is all items in the list output to a single comma delimted list.
我的想法...1. 将列表传递给一个方法.2.使用stringbuilder迭代列表并附加逗号3.测试最后一个字符,如果是逗号,则删除.
My thoughts... 1. pass the list to a method. 2. Use stringbuilder to iterate the list and append commas 3. Test the last character and if it's a comma, delete it.
你有什么想法?这是最好的方法吗?
What are your thoughts? Is this the best way?
如果将来我不仅要处理整数(我当前的计划),还要处理字符串、长整数、双精度数、布尔值等,我的代码将如何更改?我想让它接受任何类型的列表.
How would my code change if I wanted to handle not only integers (my current plan) but strings, longs, doubles, bools, etc, etc. in the future? I guess make it accept a list of any type.
推荐答案
框架已经为我们做的事情真是太神奇了.
It's amazing what the Framework already does for us.
List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());
对于一般情况:
IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());
如您所见,实际上并没有什么不同.请注意,您可能需要将 x.ToString()
实际用引号括起来(即,""" + x.ToString() + """
) 以防 x.ToString()
包含逗号.
As you can see, it's effectively no different. Beware that you might need to actually wrap x.ToString()
in quotes (i.e., """ + x.ToString() + """
) in case x.ToString()
contains commas.
有关此轻微变体的有趣阅读:请参阅埃里克·利珀特 (Eric Lippert) 博客上的逗号狡辩.
For an interesting read on a slight variant of this: see Comma Quibbling on Eric Lippert's blog.
注意:这是在 .NET 4.0 正式发布之前编写的.现在我们只能说
Note: This was written before .NET 4.0 was officially released. Now we can just say
IEnumerable<T> sequence;
string csv = String.Join(",", sequence);
使用重载 String.Join
.此方法会自动将每个元素 x
投影到 x.ToString()
.
using the overload String.Join<T>(string, IEnumerable<T>)
. This method will automatically project each element x
to x.ToString()
.
这篇关于将通用列表转换为 CSV 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!