CSharp - Use Single operator with condition

Introduction

Instead of calling the Where operator to ensure a single element is in the sequence, we can provide the same sequence filtering operation in the Single operator.

If Single operator ends up with no element to return, an InvalidOperationException is thrown.

Demo

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

        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

Related Topic