Deferred/Lazy execution: This type of a statement is executed only when the output is a necessity to proceed further in the program; until then, the execution can wait! This is the standard way in which most Language Integrated Queries (LINQ) are executed.
Deferred Execution is extremely helpful in scenarios where you don’t need the entire output to be computed at a point of time. This is made possible through the use of interation over an IEnumerable having a yield functionality. Continue reading
There an interesting variations how Linq operators executes and in this post we are going to learn both Deferred execution and immediate execution.
What is Deferred Execution?
In the Deferred execution query will be executed and evaluated at the time of query variables usage. Let’s take an example to understand Deferred Execution better. Continue reading
.First() will throw an exception if there’s no row to be returned, while .FirstOfDefault() will return a NULL value instead. .FirstOfDefault() will simply return either null (reference types) or the default value of the value type. (e.g like ‘0’ for an int.) .FirstOfDefault() is preferred when you’re not sure if you’re going to get results out of your query. When logically the data should be there, exception handling can be considered. Between .First() and .FirstOfDefault(), you should use .First() when you’re sure that an element exists and if it doesn’t, then there’s an error.
someList.First(); // exception if collection is empty. someList.FirstOrDefault(); // first item or default(Type)
- Returns the first element of a sequence
- Throws exception: There are no elements in the result
- Use when: When more than 1 element is expected and you want only the first
- Returns the first element of a sequence, or a default value if no element is found
- Throws exception: Only if the source is null
- Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty