When to use .First and when to use .FirstOrDefault with LINQ?

后端 未结 14 1673
无人共我
无人共我 2020-11-22 09:09

I\'ve searched around and haven\'t really found a clear answer as to when you\'d want to use .First and when you\'d want to use .FirstOrDefault wit

14条回答
  •  忘掉有多难
    2020-11-22 09:25

    First()

    1. Returns first element of a sequence.
    2. It throw an error when There is no element in the result or source is null.
    3. you should use it,If more than one element is expected and you want only first element.

    FirstOrDefault()

    1. Returns first element of a sequence, or a default value if no element is found.
    2. It throws an error Only if the source is null.
    3. you should use it, If more than one element is expected and you want only first element. Also good if result is empty.

    We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...

    UserInfo Table

    How to use First()

    var result = dc.UserInfos.First(x => x.ID == 1);
    

    There is only one record where ID== 1. Should return this record
    ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

    var result = dc.UserInfos.First(x => x.FName == "Rahul");   
    

    There are multiple records where FName == "Rahul". First record should be return.
    ID: 7 First Name: Rahul Last Name: Sharma Email: xyz1@xyz.com

    var result = dc.UserInfos.First(x => x.ID ==13);
    

    There is no record with ID== 13. An error should be occur.
    InvalidOperationException: Sequence contains no elements

    How to Use FirstOrDefault()

    var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);
    

    There is only one record where ID== 1. Should return this record
    ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

    var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");
    

    There are multiple records where FName == "Rahul". First record should be return.
    ID: 7 First Name: Rahul Last Name: Sharma Email: xyz1@xyz.com

    var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);
    

    There is no record with ID== 13. The return value is null

    Hope it will help you to understand when to use First() or FirstOrDefault().

提交回复
热议问题