Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can select first 3 item of list<>

Tags:

c#

linq

I'm using this code for get all news:

List<aspnet_News> allNews = context.aspnet_News.OrderByDescending(i => i.NewsId).ToList();

How I can select first 3 items of this list and bind into a Datalist, please help, thanks...

like image 497
Farhood Avatar asked Oct 15 '25 23:10

Farhood


1 Answers

You can use the Take() method

List<aspnet_News> allNews = context.aspnet_News.OrderByDescending(i => i.NewsId)
                                               .Take(3)  // Takes the first 3 items
                                               .ToList();

It'll also handle the case where the list contains less than 3 items and take them only.

like image 144
Elisha Avatar answered Oct 17 '25 11:10

Elisha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!