Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Take() question

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?

like image 590
chobo2 Avatar asked Sep 01 '09 18:09

chobo2


3 Answers

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

like image 91
Daniel Earwicker Avatar answered Nov 08 '22 16:11

Daniel Earwicker


That null reference exception is only if you are doing that against an object source such as:

List<MyObject> myList = null;
myList.Take(5); // this would produce the error, of course

When you are doing Linq to SQL it'll return an EMPTY enumerator of your data, not a null reference. On the same token, if you are attempting to take more than is available it'll only take up the amount available. I use this method to page data in some instances and definitely a lot of the time when I'll ask for more records than the list has available.

like image 40
Fooberichu Avatar answered Nov 08 '22 16:11

Fooberichu


Take will through an exception if the object invoking it is null. Chances are you will not have a null object, and having no or less rows is not the same (I am sure you understand the semantics).

If you are using a Linq to SQL context and querying in the fashion of

Context.MyTable.Where(x => x.ID > 0).Take(2);  

in the case of the Where returning zero results, you will not get a null exception, because your query has not yet been executed, then in the case of it only containing 1 result, you will end up only getting 1 result back. Take limits the amount of records returns.

like image 26
Quintin Robinson Avatar answered Nov 08 '22 16:11

Quintin Robinson