CSharp - LINQ SingleOrDefault

Introduction

The SingleOrDefault operator returns default value when an element is not found.

Prototypes

There are two prototypes we cover. The First SingleOrDefault Prototype

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

This version of the prototype returns the only element found in the input sequence.

If the sequence is empty, default(T) is returned.

For reference and nullable types, the default value is null.

If more than one element is found, an InvalidOperationException is thrown.

The second prototype of the SingleOrDefault operator uses a predicate to determine which element should be returned.

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

Exceptions

  • ArgumentNullException is thrown if any arguments are null.
  • InvalidOperationException is thrown if the operator finds more than one element for which the predicate returns true.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   www  . ja  va  2s  . com
{
    static void Main(string[] args)
    {
        Student emp = Student.GetStudentsArray()
          .Where(e => e.id == 5).SingleOrDefault();

        Console.WriteLine(emp == null ? "NULL" :
          string.Format("{0} {1}", emp.firstName, emp.lastName));

        emp = Student.GetStudentsArray()
          .Where(e => e.id == 4).SingleOrDefault();

        Console.WriteLine(emp == null ? "NULL" :
          string.Format("{0} {1}", emp.firstName, emp.lastName));
    }
}

class Student
{
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student { id = 1, firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student { id = 2, firstName = "Windows", lastName = "Python" });
        al.Add(new Student { id = 3, firstName = "Application", lastName = "HTML" });
        al.Add(new Student { id = 4, firstName = "David", lastName = "Visual" });
        al.Add(new Student { id = 101, firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student[] GetStudentsArray()
    {
        return ((Student[])GetStudentsArrayList().ToArray());
    }
}

Result

Related Topics