对象列表转换为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; }
}
和我有测试对象
List<Test>testobjs=new List();
现在我想将其转换成CSV在以下格式:
Now I would like to convert it into csv in following format:
1,约翰格里沙姆,9/5 / 2014,9 / 5 / 2014,1356,0\\\
2,斯蒂芬·金,9/3 / 2014,9 / 9 / 2014,1367,0\\\
3,造雨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屋!