snippetcsharpCritical
How to get first N elements of a list in C#?
Viewed 0 times
howlistgetelementsfirst
Problem
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
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.)Solution
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);Code Snippets
var firstFiveItems = myList.Take(5);var secondFiveItems = myList.Skip(5).Take(5);var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);Context
Stack Overflow Q#319973, score: 984
Revisions (0)
No revisions yet.