LINQ First Query Operator
By Peter Bromberg
LINQ First Query Operator returns the first element of a sequence.
This member is overloaded.
First<TSource>(IEnumerable<TSource>) Returns the first element of a sequence.
First<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) Returns the first element in a sequence that satisfies a specified condition.
// 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);
LINQ First Query Operator (531 Views)