We can use the Single extension method of LINQ to return the only element in a sequence that satisfies a specified condition. However the Single 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 SingleOrDefault extenion method which would return the default value of a type instead of throwing the System.InvalidOperationException.
Also, both Single as well as SingleOrDefault extension methods would throw the System.InvalidOperationException when more than one element in a sequence satisfy a specified condition. We can use First or Last extensions methods of LINQ in such scenarios.
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.Single(i => i == 1);
// Returns the default value of int which is 0
// since no element in the list equals 4
value = l.SingleOrDefault(i => i == 4);
// Throws System.InvalidOperationException
// since no element in the list equals 4
value = l.Single(i => i == 4);
// Throws System.InvalidOperationException
// since both 5 and 3 are greater than 1
value = l.Single(i => i > 1);
value = l.SingleOrDefault(i => i > 1);
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.Single(Function(i) i = 1)
' Returns the default value of int which is 0
' since no element in the list equals 4
value = l.SingleOrDefault(Function(i) i = 4)
' Throws System.InvalidOperationException
' since no element in the list equals 4
value = l.Single(Function(i) i = 4)
' Throws System.InvalidOperationException
' since both 5 and 3 are greater than 1
value = l.Single(Function(i) i > 1)
value = l.SingleOrDefault(Function(i) i > 1)
Cheers,
Raj
~~~ CODING FOR ETERNITY !!! ~~~