Difference Between First() and FirstOrDefault() in LINQ:-

FIRST()

It returns First element value from collection of elements or a sequence. It also returns first element of sequence when you specified condition. If result has no element than it will throws InvalidOperationException.

WHEN TO USE FIRST()

When you know that result contain more than 1 element expected and you should only the first element of sequence.

FIRSTORDEFAULT()

FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.

WHEN TO USE FIRSTORDEFAULT()

When you know that output result contain more than 1 element and you should only the first element. Default value should be returned if no element is found.

Example

results matching ""

    No results matching ""