C# SingleorDefault() Method

The SingleOrDefault() method in C# returns a single specific element from a sequence. If no element is found, it returns the default value for the type. If multiple elements are found, it throws an exception.

This method is part of LINQ and can be used with any IEnumerable<T> collection. It's particularly useful when you expect exactly zero or one element in the result.

Syntax

Following is the basic syntax for SingleOrDefault()

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

With a predicate condition −

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

Parameters

  • source − The input sequence to search.

  • predicate (optional) − A function to test each element for a condition.

Return Value

Returns the single element that satisfies the condition, or the default value if no such element exists. For reference types, the default value is null. For value types, it's the default value (e.g., 0 for integers).

Using SingleOrDefault() with Arrays

Example

using System;
using System.Linq;

public class Demo {
    public static void Main() {
        string[] str1 = { "one" };
        string[] str2 = { };
        
        string res1 = str1.SingleOrDefault();
        Console.WriteLine("Result from non-empty array: " + res1);
        
        string res2 = str2.SingleOrDefault();
        Console.WriteLine(String.IsNullOrEmpty(res2) ? "Empty array result: null" : res2);
    }
}

The output of the above code is −

Result from non-empty array: one
Empty array result: null

Using SingleOrDefault() with Predicates

Example

using System;
using System.Linq;

public class Student {
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Demo {
    public static void Main() {
        Student[] students = {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 22 },
            new Student { Name = "Charlie", Age = 19 }
        };
        
        var student = students.SingleOrDefault(s => s.Age == 22);
        Console.WriteLine(student != null ? $"Found: {student.Name}, Age: {student.Age}" : "Not found");
        
        var notFound = students.SingleOrDefault(s => s.Age == 25);
        Console.WriteLine(notFound != null ? $"Found: {notFound.Name}" : "Student with age 25: Not found");
    }
}

The output of the above code is −

Found: Bob, Age: 22
Student with age 25: Not found

Exception Handling with SingleOrDefault()

Example

using System;
using System.Linq;

public class Demo {
    public static void Main() {
        int[] numbers = { 1, 2, 3, 2, 4 };
        
        try {
            int result = numbers.SingleOrDefault(x => x == 2);
            Console.WriteLine("Result: " + result);
        }
        catch (InvalidOperationException ex) {
            Console.WriteLine("Exception: " + ex.Message);
        }
        
        int safeResult = numbers.SingleOrDefault(x => x == 5);
        Console.WriteLine("Safe result (not found): " + safeResult);
    }
}

The output of the above code is −

Exception: Sequence contains more than one matching element
Safe result (not found): 0

SingleOrDefault() vs Single() vs FirstOrDefault()

Method No Elements One Element Multiple Elements
Single() Exception Returns element Exception
SingleOrDefault() Returns default Returns element Exception
FirstOrDefault() Returns default Returns element Returns first element

Conclusion

The SingleOrDefault() method is ideal when you expect exactly zero or one matching element in a collection. It safely handles empty collections by returning the default value, but throws an exception if multiple elements match the condition, ensuring data integrity.

Updated on: 2026-03-17T07:04:35+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements