Difference Between First() and FirstOrDefault() in LINQ

LINQ Is becoming Important Part For Developers..But For New People who Are New To LINQ IS Difficult To Understand Difference Between Many Similar Syntaxes like First() and FirstOrDefault(),Single() and SingleOrDefault() etc.

Here I am going To Explain Difference Between First(0 and FirstOrDefault().

At The Time Of Interview And using LINQ its necessary To Understand Differences Between First() and FirstORDefault().It IS Commonly Used Syntax While Using LINQ().

Here Is Sample Table.

Member

ID Name Year Address Income UserName
1 PQR 2010-2011 C 50000 S123
2 PQR 2012-2013 C 180000 S123
3 XYZ 2013-2014 B 200000 S789
4 ABC 2013-2014 A 350000 S253

A. First()

  1. When we Use First() in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Expression in Where Clause then It Will Throw You Exception as: InvalidOperationException: Sequence contains no elements.
    1. Var x=(from m in Member  
    2. Where m.UserName=’S000’  
    3. Select m.Name,m.Income,m.Year ).First()  
    In The Member table There Is no Such Record Which Will Match the expression so Above Query will Throw: InvalidOperationException: Sequence contains no elements.

    We Can Handle This Exception In C# by using try Catch like:
    1. try  
    2. {  
    3.    Var x=(from m in Member  
    4.    Where m.UserName=’S000’  
    5.    Select m.Name,m.Income,m.Year  
    6.    ).First()  
    7.   
    8. }  
    9. catch (InvalidOperationException ex)  
    10. {  
    11.    Console.WriteLine(ex.Message);  
    12. }  
  2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

    i.e:
    1. Var x=(from m in Member  
    2. Where m.UserName=’s123’  
    3. Select m.Name,m.Income,m.Year).First()  
    Then You Will get The Result Like:

    PQR 2010-11 50000 S123

  3. First() returns First Element Of Sequence.

  4. First() throws Exception when There IS No element Presnt In Table.

B. FirstORDefault():

  1. When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null).
    1. Var x=(from m in Member  
    2. Where m.UserName=’S000’  
    3. Select m.Name,m.Income,m.Year ).FirstOrDefault()  
    In The Member table There Is no Such Record Which Will Match the expression so Above Query will Return Default value as Null but Not An Exception.

    But when we use above code in c# then it might throw an Exception like:
    1. Console.WriteLine(x.Name);  
    It Will Throw An Exception ( because x has Got Null Value because Of Absence Of Record In Table):
    “object reference not set to an instance of an object”.

    We Can Handle This Exception In C# by using try Catch like:
    1. try  
    2. {  
    3.    Var x=(from m in Member  
    4.    Where m.UserName=’S000’  
    5.    Select m.Name,m.Income,m.Year ). FirstOrDefault ()  
    6.    If(x!=null)  
    7.    {  
    8.        Console.WriteLine(x.Name);  
    9.    }  
    10.    else  
    11.    {  
    12.      Console.WriteLine("No Record Found");  
    13.    }  
    14. }  
    15. catch (Exception ex)  
    16. {  
    17.    Console.WriteLine(ex.Message);  
    18. }  
  2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

    i.e
    1. Var x=(from m in Member  
    2. Where m.UserName=’S123’  
    3. Select m.Name,m.Income,m.Year ).FirstOrDefault()  
    Then You Will get The Result Like:

    PQR 2010-11 50000 S123

  3. FirstOrDefault () returns First Element Of Sequence.

  4. FirstOrDefault () does not throws Exception when There IS No element Present in Table.
Ebook Download
View all
Learn
View all