Nathan Koop
Nathan Koop

Reputation: 25197

Write a CSV file

I have a class that I've written in C# and decorated with FileHelpers attributes

[DelimitedRecord(","), IgnoreFirst(1)]
class UserAndValues
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<UserFavourites> Favourites {get;set;}

    public UserAndValues()
    { }
}

class UserFavourites
{
    public int Id {get;set;}
    public string Title {get;set;}
}

I then call the CSV writer

var engine = new FileHelperEngine<UserAndValues>();
engine.WriteFile(myPath, myListOfUsers);

I get the following error:

The field: 'k__BackingField' has the type: ICollection`1 that is not a system type, so this field need a CustomConverter ( Please Check the docs for more Info).

I would like to write out a file that basically looks like

UserId, FirstName, LastName, Favourite1Id, Favourite1Title, Favourite2Id, Favourite2Title...  
1, Joe, Smith, 1, Random Title, 2, More Title, ...

The favourites collection could be 10-50 records deep and changes based on the file.

I will not need to read this file, just write it.

How can I generate a CSV using the above class? (I can modify the class structure)

Upvotes: 2

Views: 814

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

Well, very untested:

class UserAndValues
{
    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [FieldConverter(typeof(MyListConverter))] 
    public ICollection<UserFavourites> Favourites {get;set;}
}

public class MyListConverter: ConverterBase 
{ 

    public override object StringToField(string from) 
    { 
      throw new NotImplemented("bad luck");
    } 

    public override string FieldToString(object fieldValue) 
    { 
       var list = fieldValue as ICollection<UserFavourites>;

        return string.Join(",", 
            list.Select(f => f.ToString()));   // customize
    }

}

Upvotes: 2

Related Questions