Advertisement
Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Feb 26

You have been doing pagination wrong in .NET 6

Автор:
Источник:
Просмотров:
581

Pagination is in front of us everyday yet we take it for granted kind of like we do with most things. It’s what chunks huge lists of data (blog posts, articles, products) into pages so we can navigate through data.

This is how you did pagination until this point.

Pagination

using System;

public class Article
{
    public int Id;
    public string Title;
    public string Content;
    public int AuthorId;
    
    public List<Article> GetArticles()
    {
        return new List<Article> {
            new Article {Id = 1, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 2, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 3, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 4, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 5, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 6, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 7, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 8, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 9, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 10, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 11, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 12, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
        };
    }
}

public class Program
{
    public static void Main()
    {
        List<Article> articles = new Article().GetArticles();
        int pageNumber = 1;
        int itemsPerPage = 5;

        IEnumerable<Article> page = articles.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage);

        Console.WriteLine($"Page: {pageNumber}");
        foreach(Article article in page)
        {
            Console.WriteLine($"    Id: {article.Id}, Title:{article.Title}, Content:{article.Content}, AuthorId:{article.AuthorId}");
        }
    }
}

And now this is how you can achieve the same result but in a more readable way using the Chunk method.

Chunk

using System;

public class Article
{
    public int Id;
    public string Title;
    public string Content;
    public int AuthorId;
    
    public List<Article> GetArticles()
    {
        return new List<Article> {
            new Article {Id = 1, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 2, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 3, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 4, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 5, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 6, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 7, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 8, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 9, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
            new Article {Id = 10, Title = "Best title one", Content = "Amazing content", AuthorId = 1},
            new Article {Id = 11, Title = "Another title", Content = "More amazing content", AuthorId = 1},
            new Article {Id = 12, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1},
        };
    }
}

public class Program
{
    public static void Main()
    {
        List<Article> articles = new Article().GetArticles();
        int pageNumber = 1;
        int itemsPerPage = 5;

        IEnumerable<Article[]> allPages = articles.Chunk(itemsPerPage);

        Console.WriteLine($"Page: {pageNumber}");
       
        foreach(Article article in allPages.ElementAt(pageNumber - 1))
        {
            Console.WriteLine($"    Id: {article.Id}, Title:{article.Title}, Content:{article.Content}, AuthorId:{article.AuthorId}");
        }
    }
}

There’s nothing wrong with using the first method to do pagination. The Chunk method is a new way of doing achieving the same result but with a cleared code. It takes only one parameter, the maximum size of each chunk (largest numbers of items per page). Is important to note that the Chunk method is only available in .NET 6.

Conclusion

This is another way to do things, another tool in your arsenal so you can use both. 

Похожее
17 апреля
Рассмотрим интересную задачу по разработке игры «Крестики Нолики» на языке C#. Наш проект будет запускаться в консоли и потребует креативное мышление для решения задачи. Ваша задача — реализовать консольную игру "крестики-нолики" с использованием языка программирования C#. Вам нужно создать игровое поле,...
Jun 5, 2023
Author: Juan Alberto España Garcia
In this section, we’ll explore the world of unit testing in C# and .NET, learn what unit testing is, why it’s important, and the landscape of testing frameworks and tools available to developers.What is Unit Testing?Unit testing is the process...
18 января 2023 г.
Автор: Savindu Bandara
What is paginationSo you may have already used this one, but you may be wondering what this pagination 😀. So as in figure 1, pagination helps you break a large number of datasets into smaller pages. For example, a storybook...
May 13, 2023
Author: Juan Alberto España Garcia
Introduction to Async and Await in C#Asynchronous programming has come a long way in C#. Prior to the introduction of async and await, developers had to rely on callbacks, events and other techniques like the BeginXXX/EndXXX pattern or BackgroundWorker.These methods...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban