Write list of objects to text file

Viewed 27218

I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data. Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere. As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

11 Answers

Try this:

Steps:

1.Get the list of Item in the Candidate Class object

2.Pass the list of Candidate in the Save method

3.Write the content in the Text files**

    public class Candidate
    {
      public string Name{get;set;}
      public string Department{get;set;}
    }        
    public void save(List<Candidate>iolist)
    {          
     var dir = @"D:\New folder\log";
     string path = System.IO.Path.Combine(dir, "items1213.txt");
     File.WriteAllLines(path, iolist.Select(o => o.Name + " " + o.Department));    
    }
Related