Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take(parameter) when collection count is less than parameter

Tags:

c#

Let's say I have a list of objects TheListOfObjects.

If I write this:

TheListOfObjects = TheListOfObjects.Take(40).ToList();

Will it crash if there are only 30 items in the list or will it just return the first 30? And when TheListOfObjects is empty, or even null?

Thanks.

like image 528
frenchie Avatar asked Apr 09 '12 13:04

frenchie


3 Answers

This is one of those where you should just try it or at least check the documentation.

Will it crash if there are only 30 items in the list or will it just return the first 30?

It will just return the first 30.

And when TheListOfObjects is empty

It will return the empty sequence.

or even null?

It will result in a ArgumentNullException.

From MSDN:

Take<TSource> enumerates source and yields elements until count elements have been yielded or source contains no more elements.

If count is less than or equal to zero, source is not enumerated and an empty IEnumerable<TSource> is returned.

And under exceptions:

Exception             Condition
ArgumentNullException source is null

In the time it took you to log on to StackOverflow, you could have either checked MSDN and got an authoritative answer (notice that some mildly incorrect or partially incomplete answers have already been posted and deleted here) or fired up Visual Studio and greased your wheels a little bit.

like image 119
jason Avatar answered Nov 16 '22 20:11

jason


MSDN says:

Take(Of TSource) enumerates source and yields elements until count elements have been yielded or source contains no more elements.

like image 26
Pavel Krymets Avatar answered Nov 16 '22 20:11

Pavel Krymets


try this

TheListOfObjects = TheListOfObjects.Take(TheListOfObjects.Count > 30 ? 30 : TheListOfObjects.Count).ToList();
like image 3
dor Avatar answered Nov 16 '22 20:11

dor