Convert a List<T> to csv file using FileHelpers

2.2k views Asked by At

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?

3

There are 3 answers

0
Cory Nelson On BEST ANSWER

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);
0
ryanyuyu On

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);
3
Zotta On

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, ...})
));