将对象转换为CSV字符串

时间:2013-12-26 17:48:45

标签: c# asp.net string object csv

我在将产品对象转换为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
... 

我错过了什么转换来获取对象上每个项目的值?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您需要覆盖ToString()方法才能获得所需的效果。否则,当您执行ToString()时,将使用基础“对象”类中x.ToString()的实现。

Object.ToString()返回您的对象所属的类的全名。

答案 2 :(得分:0)

我认为您正在尝试以csv格式获取字符串列表/数组。

我会覆盖ToString()

class Product
{
    public override string ToString()
    {
        return ProductName + "," + Price.ToString() + "," + boolProperty.ToString();
    }
}

var q = (from d in data select d.ToString()).ToArray()

或类似

var q = (from d in data 
        select new { d.ProductName + "," + Price.ToString() +
               "," + boolProperty.ToString() } )
        .ToArray()