简体   繁体   中英

Convert a List<T> to csv file using FileHelpers

I have a class like so

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

This is then converted to a list of the type above with data. I want to use filehelpers to convert my list object to a csv string.

Currently I am doing this

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

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

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

This is giving me an error

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

The other error is :

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

How do I fix this?

If the type is known and very simple, you can do it without any external Libraries:

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

Instead of this:

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

You want this:

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

The compile errors are with this syntax:

new MyObject[]  { objList };

The curly braces are what's known as a 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()

As others have pointed out, the .WriteString is looking for any IEnumerable anyway, so just passing your existing List<MyObject> is fine. Also, the generic type of the FileHelperEngine<T> is expecting the type you want to write out, which is just MyObject and not the collection.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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