# Filtering

* Where()
* Skip()
* Take()
* First()&#x20;
* FirstOrDefault()&#x20;
* Last()&#x20;
* LastOrDefault()&#x20;
* Single()&#x20;
* SingleOrDefault()

```csharp
// Some code
var customers = Customers.Where(x => x.FirstName.StartsWith("T"))
                //.Skip(2)
                //.Take(2)
                //.First()
                //.FirstOrDefault() 
                //.Last()
                //.LastOrDefault()
                //.Single()
                //.SingleOrDefault();
```

Notes:

*   The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data( Similar with Last() vs LastOrDefault())

    <figure><img src="https://1722711354-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwNXdoUkfmcozr29fRrfb%2Fuploads%2F7foUrzPE0LAf2TEo2I4S%2FEF2.png?alt=media&#x26;token=5fb54d0c-5a1b-4160-9327-23758be5179e" alt=""><figcaption><p>.First()</p></figcaption></figure>



    <figure><img src="https://1722711354-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwNXdoUkfmcozr29fRrfb%2Fuploads%2FrcElSSu5IEyHdiUpvoJ2%2FFirstEf2.png?alt=media&#x26;token=26176bd5-6990-44e0-b81f-699500ee21e5" alt=""><figcaption><p>.FirstOrDefault()</p></figcaption></figure>


* Different between FirstOrDefault vs SingleOrDefault
  *   If your result set returns 0 records:

      * `SingleOrDefault` returns the default value for the type (e.g. default for int is 0)
      * `FirstOrDefault` returns the default value for the type

      If you result set returns 1 record:

      * `SingleOrDefault` returns that record
      * `FirstOrDefault` returns that record

      If your result set returns many records:

      * `SingleOrDefault` throws an exception
      * `FirstOrDefault` returns the first record

      Conclusion:

      If you want an exception to be thrown if the result set contains many records, use `SingleOrDefault`.

      If you always want 1 record no matter what the result set contains, use `FirstOrDefault`
*   `Single()` will raise an exception if no row found. `SingleOrDefault()` will instead return the default value (null for reference types, 0 for ints, \0 for chars etc\`).

    Use `Single()` in one of two cases:

    1. When not getting a row is something that should not happen, and if it does, it means something is wrong.
    2. When you are dealing with value types (ints, chars, etc'), and the default value might be a valid value in your values system (for instance, if you are getting `0` for an int but can't tell if it's because you got no row back or it's a valid value.

    Use `SingleOrDefault()` for any other case. If the row is not found, you'll need to compare the value you get to it's default value.
