LINQ First Query Operator
By Peter Bromberg
The First operator returns the first element of a sequence. If you don't want an exception thrown when there is no first elements in the sequence (or no first element that passes the predicate function), use the FirstOrDefault operator instead.
int[] nums = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };
int num1 = nums.First<int>();
int num2 = nums.First<int>(x => x > 50);
int num3 = nums.FirstOrDefault<int>(x => x > 5000);
Console.WriteLine(
num1.ToString() + "-" +
num2.ToString() + "-" +
num3.ToString());
LINQ First Query Operator (487 Views)