Linq By Example


Returns the first element of an Enumerable, but will return default(T) if no element is found.

Multiple Matching Elements

If multiple matching elements are found, only the first will be returned. If you require validation that there is only one item matching, you should use Single or SingleOrDefault instead.
using System;
using System.Collections.Generic;
using System.Linq;

var integerList = new List { 1, 2, 3, 4, 4, 5 };
var element = integerList.FirstOrDefault(x => x == 4);


No Matching Element

It is important to understand that if an element is not found using FirstOrDefault, the return is default(T) which may not specifically be null. Null will be returned if the type is a reference type, however for value types, this is their "default" value. For example, integer will be 0 if no element is found.

If you require an exception to be thrown if an element is not found, use First.