FirstOrDefault

The following demonstrates First versus FirstOrDefault:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int firstBigError = numbers.First(n => n > 10); // Exception 
        int firstBigNumber = numbers.FirstOrDefault(n => n > 10); // 0

        Console.WriteLine(firstBigError);
        Console.WriteLine(firstBigNumber);
    }
}

The output:


Unhandled Exception: System.InvalidOperationException: Sequence contains no matching element
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
   at Program.Main() in c:\g\Program.cs:line 11
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.