How to retrieve last 5 records using LINQ method or query expression in C#

不羁岁月 提交于 2019-11-29 05:34:54

LINQ

var lastFiveProducts = (from p in products 
                        orderby p.ProductDate descending
                        select p).Take(5);

Lambda

var lastFiveProducts = products.OrderByDescending(p => p.ProductDate).Take(5);

Which ever you prefer.

.Skip(count - 5);

or

.Reverse().Take(5).Reverse()

The simplest approach is to reverse your ordering (e.g. use orderby foo descending) and then use Take(). For example:

var recentProducts = products.OrderByDescending(x => x.CreationDate)
                             .Take(5);

or in query expression form (which I wouldn't use for simple queries which are more easily expressed in the above form):

var recentProducts = (from product in products
                      orderby product.CreationDate descending
                      select product).Take(5);

Install MoreLINQ Package, then:

CollectionName.TakeLast(5);
Jai

This is for selecting the last 5 with ascending

var query = from tbl in  (from tbl1 in object.Table orderby
tbl1.Column descending select tbl1).Take(5)  orderby tbl.Column
ascending  select tbl;
user956094

Code:

INT[]number = new int[] {3,6,8,2,3,7,0,2,5}

var result= (from r in number select r).reverse().take(5);

result: 5 2 0 7 3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!