1

I have the followings:

Class Pet

public string PetType {get; set;}
public string PetName {get; set;}
public int PetAge {get; set;}

Class Person

public string Name {get; set;}
public int Age {get; set;}
public List<Pet> ListOfPets {get; set;}

Class ViewModel

public ObservableCollection<Person> People {get; set;}

I wish to serialize the People object into a csv file.

Can such task be achieved?

I found a CSV Serializer which can only handle strings.

Idanis
  • 1,918
  • 6
  • 38
  • 69
  • 1
    https://www.nuget.org/packages/LinqToCsv/ and http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library – huysentruitw Jul 06 '16 at 09:18
  • 1
    How do you expect the `ListOfPets` to be inside your csv file ? – Zein Makki Jul 06 '16 at 09:26
  • 1
    I don't understand the confusion, the question clearly states: *I wish to serialize the People object into a csv file.* – huysentruitw Jul 06 '16 at 09:37
  • 1
    Possible duplicate of [Is there such thing as a CSV Serializer? (similar to XmlSerializer)](http://stackoverflow.com/questions/11123995/is-there-such-thing-as-a-csv-serializer-similar-to-xmlserializer) – huysentruitw Jul 06 '16 at 09:38
  • You are creating a text file that can be complicated to read and parse. One method you can use is to add the class name to each csv line so when the file is read there is a way of determining if a csv line is a Pet or a Person. I've been parsing text files like this for over 40 years and it can be done. But you have to remember that any file that is written also has to be read. Always consider when you write a file make it as easy as possible to read back. – jdweng Jul 06 '16 at 09:50
  • CSV is supposed to be a *simple, flat* format, and all tools expect it to be a simple, flat format. You'll have to export persons and pets to separate files. There are a lot of NuGet packages that can write to CSV. [CsvHelper](https://joshclose.github.io/CsvHelper/) is just one of them. – Panagiotis Kanavos Jul 06 '16 at 11:12

2 Answers2

0

A csv-file is two-dimensional, you cannot include a third dimension (the pets). You could manually append the pets one by one but you will loose the fixed column count of the csv file

Like this

[Name],[Age],[Pet1Type][Pet1Name],[Pet1Age],[Pet2Type][Pet2Name],[Pet2Age]
[Name],[Age],[Pet1Type][Pet1Name],[Pet1Age]
[Name],[Age],[Pet1Type][Pet1Name],[Pet1Age],[Pet2Type][Pet2Name],[Pet2Age,[Pet3Type][Pet3Name],[Pet3Age]

But it will be harder to consume afterwards.

Pier
  • 81
  • 4
-1

After the edit it is clear OP is interested in serializing in CSV format so i can suggest to try out CsvMapper.

var csv = new CsvWriter( textWriter );
csv.WriteRecords( list );
Mauro Sampietro
  • 2,739
  • 1
  • 24
  • 50