简体   繁体   English

DataContract对象列表转换为CSV字符串

[英]DataContract object list to CSV String

I have a list of Product(like below ) object and I want to convert csv string from this object 我有一个Product(如下面的 )对象的列表,我想从该对象转换csv字符串

[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 结果 在此处输入图片说明

What I should I for here to get a correct csv result 我在这里应该得到正确的csv结果

Check this line you have: sb.Append(String.Join(",", obj)); 检查以下行: 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)); 尝试类似sb.Append(String.Join(",", obj.Name)); for example to append the list of names 例如附加名称列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM