Paging in Order BY using LINQ

This is a simple way of doing the paging in LINQ. If I do the paging before the ORDER BY then it will give me different result set. The paging is should be after the ORDER BY Statement. So you sort first then you paging it.

        /// 
        /// to get all the have your say using paging based on optional parameter
        /// of isapproved and sorted descending based on the posted date
        /// 
        /// 
        /// 
        /// 
        /// 
        public IQueryable HaveYourSaySelectApproved(bool? IsApproved, int startPage, int pageSize)
        {
            var haveyoursay = from h in HaveYourSayContext.HaveYourSays
                                      orderby h.DatePosted descending
			select h;

            if (IsApproved.HasValue)
            {
                haveyoursay = from h in HaveYourSayContext.HaveYourSays
                              where (h.IsApproved == IsApproved.Value)
                              orderby h.DatePosted descending
                              select h;
            }

	return haveyoursay.Skip(startPage * pageSize).Take(pageSize);
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s