将可枚举到csv文件 [英] Writing enumerable to csv file

查看:166
本文介绍了将可枚举到csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个类为例

p>

  public class Test 
{
public Test()
{
data = new float [] {0,1,2,3,4};
}
public float [] data {get; set;}
}


$ b b

i希望在单独的单元格中使用每个数组值写入数据。我有一个自定义转换器,而不是提供一个单元格的所有值。



我做错了什么?

  public class DataArrayConverter< T> :ITypeConverter 
{
public string ConvertToString(TypeConverterOptions options,object value)
{
var data =(T [])value;

var s = string.Join(,,data);

}

public object ConvertFromString(TypeConverterOptions options,string text)
{
throw new NotImplementedException();
}

public bool CanConvertFrom(Type type)
{
return type == typeof(string);
}

public bool CanConvertTo(Type type)
{
return type == typeof(string);
}
}


解决方案

,它不工作这样。由于您在转换器中返回,它将引用该字段,因为它是单个字段的一部分。



  foreach()是一个非常简单的方法, var test in list)
{
foreach(test.Data中的var item)
{
csvWriter.WriteField(item);
}

csvWriter.NextRecord();
}

更新

版本3支持读取和写入IEnumerable属性。


I'm sure its very straightforward but I am struggling to figure out how to write an array to file using CSVHelper.

I have a class for example

public class Test
{
public Test()
{
data = new float[]{0,1,2,3,4};
}
 public float[] data{get;set;}
}

i would like the data to be written with each array value in a separate cell. I have a custom converter below which is instead providing one cell with all the values in it.

What am I doing wrong?

public class DataArrayConverter<T> : ITypeConverter
{
    public string ConvertToString(TypeConverterOptions options, object value)
    {
        var data = (T[])value;

       var s = string.Join(",", data);

    }

    public object ConvertFromString(TypeConverterOptions options, string text)
    {
        throw new NotImplementedException();
    }

    public bool CanConvertFrom(Type type)
    {
        return type == typeof(string);
    }

    public bool CanConvertTo(Type type)
    {
        return type == typeof(string);
    }
}

解决方案

Unfortunately, it doesn't work like that. Since you are returning , in the converter, it will quote the field, as that is a part of a single field.

Currently the only way to accomplish what you want is to write manually, which isn't too horrible.

foreach( var test in list )
{
    foreach( var item in test.Data )
    {
        csvWriter.WriteField( item );
    }

    csvWriter.NextRecord();
}

Update

Version 3 has support for reading and writing IEnumerable properties.

这篇关于将可枚举到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆