Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I would like to use Linq to query a bus schedule in my project, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?

More generally, how can I take a slice of a list in C#? (In Python I would use mylist[:5] to get the first 5 elements.)

like image 419
RexE Avatar asked Nov 26 '08 07:11

RexE


3 Answers

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
like image 54
Matt Hamilton Avatar answered Nov 09 '22 17:11

Matt Hamilton


In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)

myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);
like image 37
netadictos Avatar answered Nov 09 '22 16:11

netadictos


Like pagination you can use below formule for taking slice of list or elements:

var slice = myList.Skip((pageNumber - 1) * pageSize)
                  .Take(pageSize);

Example 1: first five items

var pageNumber = 1;
var pageSize = 5;

Example 2: second five items

var pageNumber = 2;
var pageSize = 5;

Example 3: third five items

var pageNumber = 3;
var pageSize = 5;

If notice to formule parameters pageSize = 5 and pageNumber is changing, if you want to change number of items in slicing you change pageSize.

like image 10
Sina Lotfi Avatar answered Nov 09 '22 16:11

Sina Lotfi