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

FirstOrNothing

Returns the first element of a sequence, or a nullable value which has no value if no element is found.

Source

<System.Runtime.CompilerServices.Extension()>
Public Function FirstOrNothing(Of T As Structure)(source As IEnumerable(Of T), match As Func(Of T, Boolean)) As Nullable(Of T)
    For Each item In source
        If match(item) Then
            Return item
        End If
    Next
    Return Nothing
End Function

Example

Dim numbers As New List(Of Integer) From {4, 32, 3, 23, 23}

Dim result = numbers.FirstOrNothing(Function(x) x > 50)

If result.HasValue Then
    Console.WriteLine(result.Value)
End If

Author: Fons Sonnemans

Submitted on: 14 dec 2011

Language: VB

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

Views: 5058