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?

4
  • 2
    What does the ExportAllProducts method do? Could you show us some code? Commented Dec 26, 2013 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? Commented Dec 26, 2013 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 Commented Dec 26, 2013 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 Commented Mar 16, 2023 at 15:09

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.