Search code examples
linqlinq-to-sqltake

LINQ Take(); how to handle when null or fewer records than requested available?


I want to filter my results to take only the X amount of records. I am wondering how does Take() work?

On this site I found: http://www.hookedonlinq.com/TakeOperator.ashx

It says Take() "Throws an ArgumentNullException if source is null." So what should I do? I can't guarantee that everytime I do a Take() I will have some records in that table or not.

So do I first have to do a count? Then do another query to make sure there is some records to grab?

Also what happens if the I have a Take(2) but only 1 record will it throw this same exception?


Solution

  • There's a difference between a null reference and an empty collection. It's fine to call Take on an empty collection. And the argument specifies a maximum number to take, so it's also fine to specify more than there are items in the collection.

    I recommend referring to MSDN for precise details like this.

    For Linq to Objects: http://msdn.microsoft.com/en-us/library/bb503062.aspx

    For Link to databases: http://msdn.microsoft.com/en-us/library/bb300906.aspx