0

I have a class, all string properties like this:

public class MyClass 
{
  public string Name {get;set;}
  public string Phone {get;set;}
  // a bunch of more fields....
{

And a list of that class List<MyClass> myListOfObjects; that I have populated it through out the program with values.

And then I have a file (csv) with headers:

Name, Phone, etc...

I want to write the contents of that myListOfObjects into that file. I was thinking just loop through them and write one row per object. But wanted to see is there a better nicer way?

Bohn
  • 26,091
  • 61
  • 167
  • 254

1 Answers1

2

You can write all your data in one shot, like

var list = new List<MyClass>();
var fileData = list.Select(row => string.Join(",", row.Name, row.Phone, row.Etc)).ToArray();

File.WriteAllLines(@"C:\YourFile", fileData);

Note: This is one way to improve the file write, but it doesn't handle un-escaped text data like Name with comma.

Arghya C
  • 9,805
  • 2
  • 47
  • 66
  • Not really a good solution, though could be if you also handle text qualifiers and string escaping. This will fail if there is a common in Name for example. – Daniel Gimenez Dec 11 '15 at 18:56
  • @DanielGimenez that's true. From the question it seems like he has already handled that, and he is looking for a "better" way than looping through each object and write to file for each. This was just to give a hint towards improving that, not handling un-escaped text data. – Arghya C Dec 11 '15 at 18:59