[LINQ Operators] SingleOrDefault

The “SingleOrDefault” operator returns the single element of a sequence, or a default value if no element is found. You can provide the predicate delegate instead of using the “Where” operator.

 

1. Sample Data Objects

To test examples, you need to include the <data classes> in your project.

 

2. “SingleOrDefault” operator

  • NonDeferred operator
  • Purpose: Element

 

3. Prototypes

public static T SingleOrDefault<T>(
  this IEnumerable<T> source)

public static T SingleOrDefault<T>(
  this IEnumerable<T> source,
  Func<T, bool> predicate)

The “SingleOrDefault()” returns the only one element of a sequence just like a “Single()” operator. It returns a default value when the sequence is empty but still throws an exception if there are more than one elements in a sequence. The “SingleOrDefault()” is used when you expect zero or only one element as a result, and is especially useful with DB queries.

 

4. Example 1 (Standard Operator)

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee emp =
  emps.Where(e => e.Name.Contains("King")).SingleOrDefault();
Console.WriteLine($"Matching Employee: {emp.Name}"); // John King

try
{
  Employee emp1 =
    emps.Where(e => e.Name.Contains("Smith")).SingleOrDefault(); // 2
}
catch
{
  Console.WriteLine("Not a single employee");
}

Employee emp2 =
  emps.Where(e => e.Name.Contains("No Such Name")).SingleOrDefault(); //0
if (emp2 == null)
{
  Console.WriteLine("No matching employee");
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “SingleOrDefault()” operator.

 

6. Example 3 (Standard Operator) – with a condition

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee emp =
  emps.SingleOrDefault(e => e.Name.Contains("King")); // John King

Console.WriteLine($"Matching Employee: {emp.Name}");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s