0

I have a list of Product(like below) object and I want to convert csv string from this object

[DataContract]
public class Product
{
    [DataMember]
    [XmlElement("title", Namespace = "")]
    public string Name { get; set; }

    [DataMember]
    [XmlElement("link", Namespace = "")]
    public string ProductUrl { get; set; }
}

below method is not give me the correct output

[WebGet(UriTemplate = "csv")]
public string GetCollectionAsCsv()
{
    if (WebOperationContext.Current != null)
    {
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv";
        WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = "attachment; filename=\"products.csv\"";
    }

    List<Product> resultList = _boutiqueManager.GetProducts();
    var sb = new StringBuilder();
    foreach (Product obj in resultList)
    {

        sb.Append(String.Join(",", obj));
    }
    return sb.ToString();

}

Result enter image description here

What I should I for here to get a correct csv result

1
  • You should define how you expect the "correct" csv to look like?
    – cnom
    Jul 9, 2015 at 13:48

1 Answer 1

1

Check this line you have:sb.Append(String.Join(",", obj)); you are appending the type of the object here, not some value.

Try something like sb.Append(String.Join(",", obj.Name)); for example to append the list of names

1
  • or alternately, override ToString() in your object to return all the desired properties in CSV Jul 9, 2015 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.