使用 FileHelpers 将 List<T> 转换为 csv 文件

Convert a List<T> to csv file using FileHelpers

我有一个class像这样

public class MyObject
{
    public string Name { get; set; }
    public string Location {get; set; }
}

然后将其转换为带有数据的上述类型的列表。我想使用 filehelpers 将我的列表对象转换为 csv 字符串。

目前我正在做这个

    List<MyObject> objList = new List<MyObject>();

    //populate objList here
    //..
    //..

    var feng = new FileHelperEngine<List<MyObject>>();
    string str1 = feng.WriteString(new MyObject[]  { objList });

这给我一个错误

Argument 1: cannot convert from 'MyObject[]' to
 'System.Collections.Generic.IEnumerable<System.Collections.Generic.List<MyObject>' 

另一个错误是:

Cannot implicitly convert type
'System.Collections.Generic.List<MyObject>'
to 'MyObject'

我该如何解决这个问题?

而不是这个:

var feng = new FileHelperEngine<List<MyObject>>();
string str1 = feng.WriteString(new MyObject[]  { objList });

你想要这个:

var feng = new FileHelperEngine<MyObject>();
string str1 = feng.WriteString(objList);

编译错误与此语法有关:

new MyObject[]  { objList };

花括号就是所谓的 collection initializer, which expect individual elements of the collection. Since you're making an array of MyObject, the initializer is expecting single object, but you're passing a collection of those instead. If in the future you really need to have an array (instead of any other IEnumerable types), just call LINQ's .ToArray()

正如其他人指出的那样,.WriteString 正在寻找任何 IEnumerable,所以只需传递现有的 List<MyObject> 就可以了。此外,FileHelperEngine<T> 的泛型类型需要您要写出的类型,即 MyObject 而不是集合。

var feng = new FileHelperEngine<MyObject>();
string str1 = feng.WriteString(objList);

如果类型已知且非常简单,则无需任何外部库即可完成:

File.WriteAllLines("output.csv",list.Select(
    obj => String.Join(", ", new Object[] {obj.Name, obj.Location, ...})
));