Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Take() to get less than count if there are no enough elements

Tags:

c#

linq

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); 
like image 778
StackOverflower Avatar asked Oct 07 '11 15:10

StackOverflower


People also ask

How do you use take and skip in Linq?

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.

What is .take in C#?

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);

Which Linq method allows you to specify the number of items to return in a sequence?

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.


2 Answers

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.

like image 170
mellamokb Avatar answered Oct 18 '22 16:10

mellamokb


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.

like image 24
BrokenGlass Avatar answered Oct 18 '22 16:10

BrokenGlass