最快的方式将对象列表转换为csv,并在新行中显示每个对象值 [英] Fastest way to convert a list of objects to csv with each object values in a new line
问题描述
我有一个类如下:
public class Test
{
public int Id {get;set;}
public string Name { get; set; }
public string CreatedDate {get;set;}
public string DueDate { get; set; }
public string ReferenceNo { get; set; }
public string Parent { get; set; }
}
我有一个Test对象列表
and I have a list of Test objects
List<Test>testobjs=new List();
现在我想将它转换为csv格式如下:
Now I would like to convert it into csv in following format:
1,John Grisham,9/5 / 2014,9 / 5 / 2014,1356,0\\\
2,Stephen King,9/3 / 2014,9 / 9 / 2014,1367,0 \\\
3,The Rainmaker,4/9 / 2014,18 / 9 / 2014,1;
"1,John Grisham,9/5/2014,9/5/2014,1356,0\n2,Stephen King,9/3/2014,9/9/2014,1367,0\n3,The Rainmaker,4/9/2014,18/9/2014,1";
我搜索转换列表到csv c#,我得到解决方案如下:
I searched for "Converting list to csv c#" and I got solutions as follows:
string.Join(",", list.Select(n => n.ToString()).ToArray())
这不会把\\\
放在需要的位置,即对于每个对象。
But this will not put the \n as needed i.e for each object
除了字符串构建之外,有没有其他最快的方法?请帮助...
Is there any fastest way other than string building to do this? Please help...
推荐答案
使用servicestack.text
Use servicestack.text
Install-Package ServiceStack.Text
然后使用字符串扩展方法 ToCsv(T)/ FromCsv()
and then use the string extension methods ToCsv(T)/FromCsv()
示例:
https://github.com/ServiceStack/ServiceStack.Text
更新:
Servicestack.Text
现在免费也在v4,以前是商业。不需要指定版本了!快乐序列化!
Update:
Servicestack.Text
is now free also in v4 which used to be commercial. No need to specify the version anymore! Happy serializing!
这篇关于最快的方式将对象列表转换为csv,并在新行中显示每个对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!