Reputation: 3
I have a program that displays books from a list (Windows Forms). You can view the information about each one when selected and add a book as well. The format in the text file the program is reading from is:
(Type,Book Name,Year,Authors,Page Count)
Example:
Book,Summertime,2014,Pete Bear/Douglas Patrick,411
Since this book has more than one author, the delimiter is '/' and all authors are put into a list called Books, from the class Book. Since Books.Authors is a list rather than a string object, I have to use a method to put in the file output. How can I finish this method to associate it properly?
private void SaveFile()
{
// Declare file destination and empty
System.IO.File.WriteAllText("myBooks2.txt", string.Empty);
// Declare a StreamWriter variable.
StreamWriter outputFile;
// Create a file and get a StreamWriter object.
outputFile = File.AppendText("myBooks2.txt");
// For each book item existing, write the outputs
for (int i = 0; i < Books.Count; i++)
{
outputFile.WriteLine(Books[i].Type + "," + Books[i].Title + "," + Books[i].Year + "," + getElementsInList(Books[i].Authors) + "," + Books[i].Pages);
}
Method for author list
private string getElementsInList(List<string> aList)
{
string elements = "";
for (int i = 0; i < aList.Count; i++)
{
}
return elements;
}
Upvotes: 0
Views: 423
Reputation: 23837
You could simply use Linq for this. ie:
void Main()
{
var books = new List<Book> {
new Book {Type="Book", Name="Summertime",Year=2014,Authors=new List<string> {"Pete Bear", "Douglas Patrick"},Pages=411},
new Book {Type="Book", Name="My Book",Year=2021,Authors=new List<string> {"You", "Me", "Him"},Pages=100},
new Book {Type="Book", Name="My Book #2",Year=2021,Authors=new List<string> {"Me"},Pages=100},
};
File.WriteAllLines(@"c:\temp\MyCSV.txt",
books.Select(b => $@"{b.Type},{b.Name},{b.Year},{string.Join("/", b.Authors)},{b.Pages}"));
}
public class Book
{
public string Type { get; set; }
public string Name { get; set; }
public int Year { get; set; }
public int Pages { get; set; }
public List<string> Authors { get; set; }
}
However, I would strongly suggest you to use a database instead, say postgreSQL or LiteDb, SQLite ...
Upvotes: 1