How to get first N elements of a list in C#?
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
.
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);
Working example:
[Test]
public void TestListLinqTake()
{
List<string> elements = new List<string>() { "storm", "earth", "fire"};
List<string> noErrorThrown = elements.Take(5).ToList();
List<string> someElements = elements.Take(2).ToList();
Assert.True(
someElements.First().Equals("storm") &&
someElements.Count == 2 &&
noErrorThrown.Count == 3);
}
Don't forget
using System.Linq;
Based on Bellarmine Head's comment