What is LINQ in C#?

What is LINQ in C# and why is use this LINQ in C# program? 

Last updated:9/23/2021 11:41:27 PM

1 Answers

Ravi Vishwakarma
Ravi Vishwakarma

LINQ is actually an extension of the .NET Framework, which provides the facility to fire collections of data in the C# programming language by creating queries similar to SQL Query. As a result in the same way we can retrieve data on the basis of specific Criteria by firing LINQ Query on Collections of Data in C# Program similar to SQL Query. The specialty of LINQ is that by using LINQ Queries, we can query data in a similar way not only from Databases but also from Collections of Program Objects, XML Documents, and other types of Data Sources.

Advantages of LINQ

1. It has full type checking at compile time.

2. We can avoid errors because it has intelligence.

3. Its query can be reused.

4. We can debug using a .NET debugger.

5. It supports filter, sorting, ordering, and grouping with much less effort.

Disadvantages of LINQ

1. Since it was written in the code we cannot make use of the Cache execution plan which is a SQL feature as we do in the stored procedure.

2. If the query is not written properly then performance is degraded.

Example 

using System;

using System.Linq;
using System.Collections.Generic;
class MyProgram
{
 static void Main(string[ ] args)
    {
  List<Student> studentList=new List<Student>(){
   new Student('John',18) ,
   new Student('Steve',20),
   new Student('Bill',12),
   new Student('Ram',58),
   new Student('Ron',18) ,
   new Student('Ashu',22),
   new Student('Shriyam',28)
  };
  var studentobject = from s in studentList
                       where s.Age > 12 && s.Age < 30
                       select new { StudentName = s.Name, StudentAge = s.Age};
  studentobject.ToList().ForEach(s => Console.WriteLine(s.StudentName +' Age is ' + s.StudentAge));

  }
}
class Student
{
 public string Name;
 public int Age;
 public Student()
 {
  this.Name=string.Empty;
  this.Age=default(int);
 }
 public Student(string name, int age)
 {
  this.Name = name;
  this.Age = age;
 }
}

Output

John Age is 18

Steve Age is 20
Ron Age is 18
Ashu Age is 22
Shriyam Age is 28

Answer