转换一个泛型列表到CSV字符串 [英] Converting a generic list to a CSV string

查看:122
本文介绍了转换一个泛型列表到CSV字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整数值(列表)的列表,并希望生成逗号分隔值的字符串。这是列表输出到一个逗号delimted列表中的所有项目。

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?

如何将我的,如果我想处理不仅整数(我目前的计划),但字符串,长材,code修改双打,布尔变量,等等,等等的未来?我想使其接受任何类型的列表。

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.

有关阅读的这个轻微变种一个有趣:请参见逗号纠缠上埃里克利珀的博客。

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&LT; T&GT;(字符串,IEnumerable的&LT; T&GT ;) 。此方法将自动项目中的每个元素 X x.ToString()

这篇关于转换一个泛型列表到CSV字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆