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.)
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);
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 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
andpageNumber
is changing, if you want to change number of items in slicing you changepageSize
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With