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

后端 未结 14 1388
无人共我
无人共我 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:43

    First()

    When you know that result contain more than 1 element expected and you should only the first element of sequence.

    FirstOrDefault()

    FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.

    0 讨论(0)
  • 2020-11-22 09:43

    This type of the function belongs to element operators. Some useful element operators are defined below.

    1. First/FirstOrDefault
    2. Last/LastOrDefault
    3. Single/SingleOrDefault

    We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.

      List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };
    

    First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.

    int result = items.Where(item => item == 2).First();

    FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.

    int result1 = items.Where(item => item == 2).FirstOrDefault();

    0 讨论(0)
提交回复
热议问题