Filtering

  • Where()

  • Skip()

  • Take()

  • First()

  • FirstOrDefault()

  • Last()

  • LastOrDefault()

  • Single()

  • SingleOrDefault()

// 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())

  • 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.

Last updated