Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is</p> <ul> <li>a semantical difference</li> <li>a performance difference</li> </ul> <p>between the two.</p> <p><strong>Semantical Difference:</strong></p> <ul> <li><code>FirstOrDefault</code> returns a first item of potentially multiple (or default if none exists).</li> <li><code>SingleOrDefault</code> assumes that there is a single item and returns it (or default if none exists). Multiple items are a violation of contract, an exception is thrown.</li> </ul> <p><strong>Performance Difference</strong></p> <ul> <li><p><code>FirstOrDefault</code> is usually faster, it iterates until it finds the element and only has to iterate the whole enumerable when it doesn't find it. In many cases, there is a high probability to find an item.</p></li> <li><p><code>SingleOrDefault</code> needs to check if there is only one element and therefore always iterates the whole enumerable. To be precise, it iterates until it finds a second element and throws an exception. But in most cases, there is no second element.</p></li> </ul> <p><strong>Conclusion</strong></p> <ul> <li><p>Use <code>FirstOrDefault</code> if you don't care how many items there are <strong>or</strong> when you can't afford checking uniqueness (e.g. in a very large collection). When you check uniqueness on adding the items to the collection, it might be too expensive to check it again when searching for those items. </p></li> <li><p>Use <code>SingleOrDefault</code> if you don't have to care about performance too much and want to make sure that the assumption of a single item is clear to the reader and checked at runtime.</p></li> </ul> <p>In practice, you use <code>First</code> / <code>FirstOrDefault</code> often even in cases when you assume a single item, to improve performance. You should still remember that <code>Single</code> / <code>SingleOrDefault</code> can improve readability (because it states the assumption of a single item) and stability (because it checks it) and use it appropriately.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload