CSharp - Use condition with SingleOrDefault operator

Introduction

Instead of filtering the elements using the Where operator, we filter them by passing a predicate to the SingleOrDefault operator.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*w  w  w .  j  av a2 s  .c o m*/
{
    static void Main(string[] args)
    {
        Student emp = Student.GetStudentsArray().SingleOrDefault(e => e.id == 4);

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

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

        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 Topic