1

I am having problems converting an object of products into a csv string.

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

This produces an output of:

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

Expected output would be like:

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

What conversion am I missing to get the values out of each item on the object?

Jim G.
  • 15,141
  • 22
  • 103
  • 166
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113
  • 2
    What does the **ExportAllProducts** method do? Could you show us some code? – Thomas C. G. de Vilhena Dec 26 '13 at 17:50
  • 3
    By default, `.ToString()` on a reference type just prints the name of the type. What is the type of `data`? Have you overridden the default behavior of `.ToString()` on it? – David Dec 26 '13 at 17:52
  • I would assume ExportAllProducts returns an array of objects and therefore the string.join returns an "{object}","{object}" sort of array and not the result join of all properties of the object – Dalorzo Dec 26 '13 at 17:57
  • Does this answer your question? [Fastest way to convert a list of objects to csv with each object values in a new line](https://stackoverflow.com/questions/25683161/fastest-way-to-convert-a-list-of-objects-to-csv-with-each-object-values-in-a-new) – Jim G. Mar 16 '23 at 15:09

3 Answers3

4

Your data variable is not a list of strings, either add a .ToString() method to that class or create a list of strings and use that.

T McKeown
  • 12,971
  • 1
  • 25
  • 32
1

You need to override ToString() method in order to have the desired effect. Otherwise, the implementation of ToString() from the base "Object" class is used when you do x.ToString().

Object.ToString() returns the full name of the class of which your object is an instance of.

asm00
  • 689
  • 5
  • 6
0

I think you're trying to get a list/array of strings in csv format.

I'd override ToString()

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

and

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

or something like

var q = (from d in data 
        select new { d.ProductName + "," + Price.ToString() +
               "," + boolProperty.ToString() } )
        .ToArray()
Vland
  • 4,151
  • 2
  • 32
  • 43