How to find the first and last data of SQL using LINQ?

How to find the first and last data of SQL Database using LINQ?

Last updated:9/24/2021 1:36:46 AM

1 Answers

Ravi Vishwakarma
Ravi Vishwakarma

We use the First and Last methods in LINQ for finding the first element and last element.

  1. First() are used to fetching the first row data from SQL and we can use the FirstOrDefault() method 
  2. Last() are used to fetching the last row data from SQL and we can use the LastOrDefault() method
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 }
  };
  List<Student> list = students.Where( stu => stu.Marks > 500).ToList();
  Console.WriteLine('\nAll value :\n');
  Console.WriteLine('{0,-10} {1,10} {2,5}','Name', 'ID', 'Marks');
  list.ForEach( student => Console.WriteLine('{0,-10} {1,10} {2,5}', student.Name, student.StudentId, student.Marks) );
  Student first = students.Where( stu => stu.Marks > 500).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 last = students.Where( stu => stu.Marks > 500).Last();
  Console.WriteLine('\nLast() :\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

All value :

Name ID Marks
Sunny 4 550
Ram 5 600
Krishna 6 700
Anupam 7 550
First() :
Name ID Marks
Sunny 4 550
Last() :
Name ID Marks
Anupam 7 550

Answer