We can use the First extension method of LINQ to return the first element in a sequence that satisfies a specified condition. However the First extension method would throw the System.InvalidOperationException when no element in a sequence satisfies a specified condition. In such a scenario, we can use the FirstOrDefault extenion method which would return the default value of a type instead of throwing the System.InvalidOperationException.
Code example (both in C# and VB.NET) with comments below:
C#:
// Create a new generic list of ints
List<int> l = new List<int>();
l.Add(1); // Add 1 to the list
l.Add(5); // Add 5 to the list
l.Add(3); // Add 3 to the list
// Returns 1 as only 1 satisfies the condition
int value = l.First(i => i == 1);
// Returns 5 although both 5 and 3 are greater than 1
// since 5 appears first in the list
value = l.First(i => i > 1);
// Returns the default value of int which is 0
// since no element in the list equals 4
value = l.FirstOrDefault(i => i == 4);
// Throws System.InvalidOperationException
// since no element in the list equals 4
value = l.First(i => i == 4);
VB.NET:
' Create a new generic list of ints
Dim l As New List(Of Integer)
l.Add(1) ' Add 1 to the list
l.Add(5) ' Add 5 to the list
l.Add(3) ' Add 3 to the list
' Returns 1 as only 1 satisfies the condition
Dim value As Integer = l.First(Function(i) i = 1)
' Returns 5 although both 5 and 3 are greater than 1
' since 5 appears first in the list
value = l.First(Function(i) i > 1)
' Returns the default value of int which is 0
' since no element in the list equals 4
value = l.FirstOrDefault(Function(i) i = 4)
' Throws System.InvalidOperationException
' since no element in the list equals 4
value = l.First(Function(i) i = 4)
Cheers,
Raj
~~~ CODING FOR ETERNITY !!! ~~~