简体   繁体   中英

Printing out unwanted spaces in the results file C#

    void PrintOutFatBooks(List<Book> books)
    {
        string[] lines = new string[books.Count];
        for (int i = 0; i < books.Count; i++)
        {
            if (books[i].Pages > 400)
            {
                lines[i] = String.Format("Book with more than 400 pages name is: {0}"
                    +", it has: {1} pages", books[i].BookName, books[i].Pages);
            }
        }
        File.WriteAllLines(@"FatBooks.csv", lines);
    }

The results print normally except it makes unwanted spaces between each of it. For example, there's the results:

Book with more than 400 pages name is: Harry Potter, it has 512 pages

Book with more than 400 pages name is: Harry Potter 2, it has 800 pages

How do I remove the big space in between 2 results (can't put a big space in between the results in stackoverflow, but there's a big space)? This is my first post in stackoverflow, so please don't be very harsh, thanks and have a beautiful day :)

The comment about a List is a little short, but the right way to go.

If you create an array the same size and only fill elements when the Pages > 400 at the same index as the book was. You only filtering the books.Pages <= 400 and leave them empty. A List<string> is dynamic on size and increase automatically.

void PrintOutFatBooks(List<Book> books)
{
    var lines = new List<string>();
    for (int i = 0; i < books.Count; i++)
    {
        if (books[i].Pages > 400)
        {
            lines.Add(String.Format("Book with more than 400 pages name is: {0}"
                +", it has: {1} pages", books[i].BookName, books[i].Pages));
        }
    }
    File.WriteAllLines(@"FatBooks.csv", lines);
}

If the assignment is all about using a for loop with an index. You should leave it like this, but a nice suggestion is using a foreach loop.

void PrintOutFatBooks(List<Book> books)
{
    var lines = new List<string>();
    foreach (var book in books)
    {
        if (book.Pages > 400)
        {
            lines.Add(String.Format("Book with more than 400 pages name is: {0}"
                +", it has: {1} pages", book.BookName, books.Pages));
        }
    }
    File.WriteAllLines(@"FatBooks.csv", lines);
}

You could also use linq for this (expert mode)

void PrintOutFatBooks(List<Book> books)
{
    File.WriteAllLines(@"FatBooks.csv", 
        books.Where(book => book.Pages > 400)
             .Select(book => $"Book with more than 400 pages name is: {book.BookName}, it has: {books.Pages} pages");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM