将List转换为csv String

时间:2017-06-06 18:38:09

标签: c#

我正在尝试将列表转换为CSV string.list有200多个属性。所以我需要属性以及值 例如
Id,name,class,lastname ....等等..
1,测试,第二,测试......等等。
2,test2,second,test2 ......等......

我用foreach追加

  foreach (var value in testData)
        {
            sb.Append(separator).Append(value);
            separator = ",";
              sb.Append(separator).Append(value);
            separator = ",";
        }

我需要传递200个属性才能增加代码行。

1 个答案:

答案 0 :(得分:0)

这是我实现的,它接受一个对象并读取属性值,然后将其格式化为csv' d字符串。

Write.WriteObject()是您如何使用它的示例。

public static class StringExtensions
{
    public static string ToCSV(this object field, bool first)
    {
        if(field != null)
        {
            string retVal = field.ToString();
            retVal = retVal.Contains(",") || retVal.Contains("\"") || retVal.Contains("\r\n") 
                ? "\"" + retVal + "\"" : retVal;
            retVal = first ? retVal : "," + retVal;
            return retVal;
        }
        else
        {
            return first ? "" : ",";
        }
    }
}

public class Format
{
    public string CommaSeparatedObject(Type layoutType, object value, bool header)
    {
        bool first = true;

        string retVal = "";
        PropertyInfo[] props = layoutType.GetProperties();

        if (header)
        {
            foreach (PropertyInfo prop in props)
            {
                retVal += prop.Name.ToCSV(first);
                first = false;
            }
        }
        else
        {
            foreach (PropertyInfo prop in props)
            {
                retVal += prop.GetValue(value).ToCSV(first);
                first = false;
            }
        }


        return retVal;
    }
}

public class Write
{
    public void WriteObject(IEnumerable<myClass> myObj)
    {
        StreamWriter sw = new StreamWriter(parameters.OutputFile, true, Encoding.ASCII, 16 * 1024);

        sw.WriteLine(new Format().CommaSeparatedObject(typeof(myClass), item, true))); //write header

        foreach(var item in myObj)
        {
            sw.WriteLine(new Format().CommaSeparatedObject(typeof(myClass), item, false)));
        }
    }
}