Sunday, May 12, 2013

Single vs SingleOrDefault

If no element is found Single throws an exception, but SingleOrDefault returns null.

Both methods throw an exception if there's more than one element in the sequence.

For example if there's more than one element SingleOrDefault() throws something like the following: System.InvalidOperationException: Sequence contains more than one element

NOTE: FirstOrDefault should be used when we have more than one element in the sequence and want only one element from it (in this case -as the name indicates- the first one) FirstOrDefault returns null when founds nothing (similar to SingleOrDefault).

public Transaction GetTransaction(Transaction transaction) {
    var transactions = GetTransactions(from: transaction.Date, to: transaction.Date);
    return transactions != null 
        ? transactions.Where(t => t.ID == transaction.ID).FirstOrDefault()
        : null;

No comments: