Take is LINQ functionality to get given number of elements from the beginning of a collection. Below you can find out how to use it.
We’ll start with creating example list of colors:
1 |
var colors = new List<string>() { "red", "green", "blue", "pink", "grey" }; |
Let’s say we want to get first three items, so need to call Take with parameter 3.
1 |
var filteredColors = colors.Take(3); |
Now print the received collection to the console:
1 2 |
foreach (var color in filteredColors) Console.WriteLine(color); |
Result:
1 2 3 |
red green blue |
When we print on screen original list, it stays unchanged:
1 2 |
foreach (var color in colors) Console.WriteLine(color); |
Result:
1 2 3 4 5 |
red green blue pink grey |