Debacle
Debacle

Reputation: 1221

C# Converting a string into multiple CSV delineated columns?

I'm working on a project where I'd like to have a C# object and export it to a CSV file.

The export works great for an object that looks like this:

public class Person 
{
   public string Name { get; set; }
   public string Height { get; set; }
   public string Address { get; set; }
   public string FavoriteColor { get; set; }
}

In the above instance, the csv code I have exports a file that looks like below:

Name    Height Address     FavoriteColor
--------------------------------- 
Debacle 6 feet 123 Hope St Yellow 
Yarn    5 feet 321 Despair Blue

But when I try to add complexity to the DO it backfires on me:

public class Person 
{
   public string Name { get; set; }
   public string Height { get; set; }
   public string Address { get; set; }
   public string FavoriteColor { get; set; }
   public List<string> Hobbies { get; set; }
}

Output looks like this:

Name    Height Address     FavoriteColor Hobbies
------------------------------------------------ 
Debacle 6 feet 123 Hope St Yellow       System.Collections.Generics.List<string> 
Yarn    5 feet 321 Despair Blue         System.Collections.Generics.List<string>

So instead of printing out the Hobbies object, it just prints off the type and memory location of the object.

I'm trying to find a way to have it grab from the list and print off something that looks more like this:

Name    Height Address     FavoriteColor Hobbie1 Hobbie2 Hobbie3
----------------------------------------------------------------
Debacle 6 feet 123 Hope St Yellow        reading writing otherstuff
Yarn    5 feet 321 Despair Blue          yes     no

But I'm coming up blank on how to dynamically generate these columns. I've changed the List object to a comma delineated string, a dictionary, etc but I can't get the desired functionality.

Is there a trick in C# that I'm missing maybe?

Thank you very much for any help!

Upvotes: 0

Views: 75

Answers (1)

JohnG
JohnG

Reputation: 9469

You are going to have to loop through the collection to get the individual hobbies. Below are two methods you can add to your Person class to help outputting the info.

public string GetHobbies() {
  StringBuilder sb = new StringBuilder();
  foreach (string hobbie in Hobbies) {
    sb.Append(hobbie + " ");
  }
  return sb.ToString();
}

public override string ToString() {
  return Name + "  " + Height + "  " + Address + "  " + FavoriteColor + "  " + GetHobbies();
}

Upvotes: 1

Related Questions