Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.First does not throw exception on empty collection

I am running a linq query that should throw an exception (based on my understanding), but it does not. There is no item in the database that fits the parameters of the query.

The following does not throw an exception, but simply returns null:

from i in Items
where i.ItemID == 25
select i.Values.First(v => v.AttribID == 69)

The following does throw an exception as expected:

(from i in Values
where i.ItemID == 25
where i.AttribID == 69
select i).First()

Through testing several different forms of the query, the only difference I can find is that .First doesn't seem to throw the exception when the lambda expression inside of returns nothing, but when .First is invoked with no parameters, it does. Please help me understand why.

To clarify...

from i in Items
where i.ItemID == 25
select i

...returns 1 item.

See linqPad results below when testing these queries:

enter image description here

enter image description here

enter image description here

like image 916
MatthewHagemann Avatar asked Dec 25 '22 06:12

MatthewHagemann


1 Answers

The first query says:

Filter Items to only include those with ItemId == 25 and from each filtered result i, select the first item v inside i.Values such that v.AttribID == 69.

Here First will not throw if e.g. Items is empty because "from each filtered result i" will process exactly zero items, so First will never be called.

The second query says:

Filter Values to only include those with ItemId == 25 and AttribId == 69 and give me the first matching item.

It's obvious that in this case if no matching items exist First cannot give you a meaningful result and will throw.

like image 67
Jon Avatar answered Jan 04 '23 19:01

Jon