Many people get confused about the difference between First vs FirstOrDefault and Single vs Single OrDefault methods in LINQ. Let me explain below difference between them.
| First() | FirstOrDefault() | Single() | SingleOrDefault() |
Description | Returns the first element of a sequence | Returns the first element of a sequence, or a default value if no element is found | Returns a single, specific element of a sequence | Returns a single, specific element of a sequence, or a default value if that element is not found |
Exception thrown when | There are no elements in the result | Only if the source is null (they all do this) | There are 0 or more than 1 elements in the result | There is more than one element in the result |
When Use | When more than 1 element is expected and you want only the first | Only if the source is null (they all do this) | If exactly 1 element is expected; not 0 or more than | When 0 or 1 elements are expected |
No comments: