Skip to main content
 首页 » 编程设计

c#之将对象转换为 CSV 字符串

2024年02月13日22开发

我在将产品对象转换为 csv 字符串时遇到问题。

var data = ProductPresenter.ExportAllProducts(); 
string csv = String.Join(",", data.Select(x => x.ToString()).ToArray()); 

这会产生以下输出:

BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts,BLL.Views.ExportAllProducts 

预期输出如下:

Small Hat, 12.10, true 
Medium Hat, 13.50, true 
Large Hat, 15.00, false 
...  

要从对象上的每个项目中获取值,我缺少什么转换?

请您参考如下方法:

您的数据变量不是字符串列表,请向该类添加 .ToString() 方法或创建字符串列表并使用它。