CSharp - LINQ Single

Introduction

The Single operator returns the one element from element sequence or a sequence matching a predicate.

Prototypes

There are two prototypes we cover. The first Single Prototype

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

Using this prototype, the Single operator enumerates the input sequence named source and returns the only element of the sequence.

The second prototype of Single allows a predicate to be passed and looks like this:

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

This version of the Single operator returns the only element it finds for which the predicate returns true.

If no elements cause the predicate to return true or multiple elements cause the predicate to return true, the Single operator throws an InvalidOperationException.

Exceptions

  • ArgumentNullException is thrown if any arguments are null.
  • InvalidOperationException is thrown if the source sequence is empty or if the predicate never returns true or finds more than one element for which it returns true.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program//from   w  w w  .j  a v a 2 s .  c  o  m
{
    static void Main(string[] args)
    {
        Student emp = Student.GetStudentsArray()
          .Where(e => e.id == 3).Single();

        Console.WriteLine("{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

Single operator is useful as long as you can ensure there will be only a single element in the sequence passed to it.

Related Topics