3

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...

walther
  • 13,466
  • 5
  • 41
  • 67
Farhood
  • 197
  • 3
  • 5
  • 9

2 Answers2

16

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.

Elisha
  • 23,310
  • 6
  • 60
  • 75
2

Use method Take() and if you need, you can use Skip() as well.

How to get first N elements of a list in C#?

Community
  • 1
  • 1
walther
  • 13,466
  • 5
  • 41
  • 67