Ads

C# Programming 30 - SingleOrDefault, FirstOrDefault, and First in LINQ

Always consider the specific requirements of your application, potential data variations, and the desired behavior when choosing between these methods in real-world scenarios.



1. SingleOrDefault:


Question: Retrieve a student with a specific ID using SingleOrDefault.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Student> students = GetStudents();

        int targetId = 3;
        var student = students.SingleOrDefault(s => s.Id == targetId);

        if (student != null)
            Console.WriteLine($"Student with ID {targetId}: {student.Name}");
        else
            Console.WriteLine($"Student with ID {targetId} not found.");

        Console.ReadKey();
    }

    static List<Student> GetStudents()
    {
        return new List<Student>
        {
            new Student { Id = 1, Name = "Alice" },
            new Student { Id = 2, Name = "Bob" },
            new Student { Id = 3, Name = "Charlie" }
        };
    }
}

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


In this example, SingleOrDefault is used to find a student with a specific ID. If there's exactly one student with the given ID, it is returned; otherwise, null is returned.

2. FirstOrDefault:


Question: Retrieve the first student whose name starts with 'A' using FirstOrDefault.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Student> students = GetStudents();

        var student = students.FirstOrDefault(s => s.Name.StartsWith("A"));

        if (student != null)
            Console.WriteLine($"First student with name starting with 'A':
            {student.Name}");
        else
            Console.WriteLine("No student found with name starting with 'A'.");

        Console.ReadKey();
    }

    // GetStudents method remains the same
}


In this example, FirstOrDefault is used to find the first student whose name starts with 'A'. If no such student is found, null is returned.

3. First:

Question: Retrieve the first student in the list.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<Student> students = GetStudents();

        var firstStudent = students.First();

        Console.WriteLine($"First student in the list: {firstStudent.Name}");

        Console.ReadKey();
    }

    // GetStudents method remains the same
}


In this example, First is used to retrieve the first student in the list. If the list is empty, it will throw an exception, so it's important to ensure that the list is not empty before using First.

These examples demonstrate the use of SingleOrDefault, FirstOrDefault, and First in different scenarios. Each method has its own purpose and is selected based on the specific requirements of the query.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !