. The first does not throw an exception in an empty collection

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

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

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

Next, an exception is thrown:

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

By testing several different request forms, the only difference I can find is that. The first does not seem to throw an exception when the lambda expression inside returns nothing, but when .First is called without parameters, it does. Please help me understand why.

To clarify...

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

... returns 1 element.

See the linqPad results below when testing these queries:

enter image description here

enter image description here

enter image description here

+4
1

:

Items , ItemId == 25, i, v i.Values v.AttribID == 69.

First , , , Items , " i" , First .

:

Values, , ItemId == 25 AttribId == 69, .

, , , First .

+9

Source: https://habr.com/ru/post/1547913/


All Articles