What is the difference between the first and single functions in LINQ?

What is the difference between the first and single functions in LINQ?

Last updated:9/24/2021 1:40:01 AM

1 Answers

Ravi Vishwakarma
Ravi Vishwakarma

First and Single operator difference

First

  1. The collection has no element then throw NoElementsException.
  2. The first function returns the first row from or top one row from the collection.
  3. The first method takes a condition to fetch elements from the collection

Single

  1. The collection has no element then throw NoElementsException and the element has more than one then return MoreThanOneElementException.
  2. The single function has checked the collection that element is single then return row.
  3. The single method takes a condition but this condition allows one row, no more than one row.

Example

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
 public static void Main()
 {
  List<Student> students = new List<Student>(){
  new Student() { StudentId = 1, Name = 'Ashu', Marks = 500 },
  new Student() { StudentId = 2, Name = 'Shyam', Marks = 300 },
  new Student() { StudentId = 3, Name = 'Shriyam', Marks = 400 },
  new Student() { StudentId = 4, Name = 'Sunny', Marks = 550 },
  new Student() { StudentId = 5, Name = 'Ram', Marks = 600 },
  new Student() { StudentId = 6, Name = 'Krishna', Marks = 700 },
  new Student() { StudentId = 7, Name = 'Anupam', Marks = 550 }
  } ;

  Student first = students.First();   Console.WriteLine('\nFirst() :\n');   Console.WriteLine('{0,-10} {1,10} {2,5}','Name', 'ID', 'Marks');   Console.WriteLine('{0,-10} {1,10} {2,5}', first.Name, first.StudentId, first.Marks);   // Student first = students.Where( stu => stu.Marks > 500).Single();   // this will throw an InvalidOperationException exception because more than 1 element in students.   Student last = students.Single( stu => stu.StudentId == 2);   Console.WriteLine('\nSingle() :\n');   Console.WriteLine('{0,-10} {1,10} {2,5}','Name', 'ID', 'Marks');   Console.WriteLine('{0,-10} {1,10} {2,5}', last.Name, last.StudentId, last.Marks);   Console.ReadLine();  } } class Student { public int StudentId { get; set; } public string Name { get; set; } public int Marks { get; set; } }

Output

First() :

Name ID Marks
Ashu 1 500
Single() :
Name ID Marks
Shyam 2 300

Answer