Pagination implementation for a blog system
int num


What does num represent exactly? Number of pages? Number of posts per page? Current page number? Properly naming the variable would help a lot in clarity here.



var postsPerPage = 3;


Turn it into a parameter with default value 3. That way you can always decide later that the user can change this without much trouble.



Instead of using 0-based pages and then adding 1 to the presentation, I would consider using the reverse: 1-based pages and subtracting 1 when determining the pages to display. In essence this would turn your loop from i = 2, name becomes unnecessary and in your controller you use int skip = (num - 1) * postsPerPage instead.



using (UnitOfWork uwork = new UnitOfWork())
{
    IEnumerable&lt;Post&gt; posts = uwork.PostRepository.GetAll().ToList();

    int totalPosts = posts.Count();
    ViewBag.pages = totalPosts / postsPerPage;
    int skip = num * postsPerPage;


    return View(posts.Skip(skip).Take(postsPerPage));
}


ViewBag.pages (note the incorrect naming convention) indicates to me a collection of pages. In your case however, a more appropriate name would be AmountOfPages.



I feel like there's room for an optimization here: what if you have 100.000 pages? Or even just 100? You will load all your items each time someone visits the frontpage and you're only doing this to show the user how many pages of items there are. In fact you're not even doing that: you won't show them past 10 pages anyway!

I would argue that maybe you should just use two queries: 

var totalPosts = uwork.PostRepository.GetAll().Count() 


which will just perform a select count(*) from posts at the database side and another query that gives you your pages: 

var pages = uwork.PostRepository.GetAll().Skip(skip).Take(postsPerPage)


Another way to keep performance in mind is to use 

uwork.PostRepository.GetAll().Take(postsPerPage * 10).ToArray();


This will you give 


The amount of posts (the exact amount being pages.Length)
The concrete posts (being pages.Skip(skip).Take(postsPerPage))


The benefit of this is that it will only call the database once (network latency is one of your demons) with the downside being that it retrieves more items than you're interested in.



Instead of looping to ViewBag.pages + 1 and possibly breaking out at i &gt;= 10, I would just loop until Math.Min(ViewBag.Pages + 1, 10).