I'd like to get 3 or less elements (in case after the Skip()
there aren't 3 elements to take).
Is it possible with linq syntax?
myFilteredList = sortedFullList .Skip(skipCount) .Take(3);
The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.
The Take() extension method returns the specified number of elements starting from the first element. Example: Take() in C# IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" }; var newList = strList.Take(2); foreach(var str in newList) Console.WriteLine(str);
In LINQ, you can count the total number of elements present in the given sequence by using the Count Method. This method returns the total number of elements present in the given sequence.
Enumerable.Take
does do that automatically. Your code sample as given should work:
Take enumerates source and yields elements until count elements have been yielded or source contains no more elements.
This should work as is with your query - Take(3)
will return 3 elements at most - but less if there are less items in the enumeration.
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