When To Use FirstOrDefault with Linq Expression

FirstOrDefault is a Linq expression that returns the first element of a sequence or a default value (which is usually null) when no element is found. First is similar, but throws an error when no element is found. FirstOrDefault is usually preferred to First because it does not throw an error unless you are sure that First is the better option.

FirstOrDefault can be used instead of Where when the first element is always used. The difference is that FirstOrDefault returns an element while Where returns a list. Then, you need to get the first element in the list. For example, the condition is filtering the primary key and therefore it returns only one record. If that is the case, FirstOrDefault is better than Where because FirstOrDefault will return null when there is no record. It would be easier to do null check.

Let’s see the example that illustrates that FirstOrDefault is more elegant than Where when we need to do null check on the filtered list.

As you can see, using Where would be too awkward. Where returns a list with one element. To check if the list is empty or not, you have to check the count. To return a list, you need to pick the first element.

On the other hand, FirstOrDefault returns an element, not a list with one element. The refactored code is more elegant.

Pretty cool.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …