ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FirstOrNull

Returns the null when there's null first element in the sequence instead of throwing an exception

Source

public static T FirstOrNull<T>(this IEnumerable<T> values) where T: class
{
    return values.DefaultIfEmpty(null).FirstOrDefault();
}

Example

using System.Reflection;
// in this example the MemberInfo for this.Name will be returned or 
// null if "this" doesn't have a member called Name 
var memberInfo = this.GetType()
.GetMembers()
.Where(m => m.Name == "Name")
.FirstOrNull();

Author: Jason Briggs

Submitted on: 30 jun. 2015

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 9237