LINQ in C#

LINQ (Language Integrated Query) is a query syntax that is used to query from a collection or data source, the query syntax is very similar to SQL. LINQ aims to solve the complexity involved with filtering, sorting and other operations with its easy to use SQL-like syntax. A LINQ query consists of 3 parts mainly, they are

  1. Data Source: This could be a collection (ArrayList, List.. etc) or Entity (Entity Framework) or ADO.NET datasets or any other format for which a LINQ provider is available.

  2. Query: Write the query using LINQ syntax and store it in a variable.

  3. Execution: Execute the query.

Let’s look at an example to understand this better,

assume we have a list of students and we want to get the students who scored above 80% and whose age is above 20 and order them by their names.

// student class
public class Student
{
    public int Age { get; set; }
    public double Percentage { get; set; }
    public string Name { get; set; }
} 

public static class Main
{
    public static void Main()
    {
        var studentsList = new List<Student>(); // 1st part -> data source
        // add students
        studentsList.Add(new Student()
        {
            Age = 22,
            Percentage = 80.23,
            Name = "toby"
        });
        studentsList.Add(new Student()
        {
            Age = 21,
            Percentage = 71.68,
            Name = "jim"
        });
        studentsList.Add(new Student()
        {
            Age = 28,
            Percentage = 86.51,
            Name = "pam"
        });
        /*
         2nd part -> query to get students who scored above 80% and age is
         above 20 and order by name
        */
        var query = from student in studentsList
                    where student.Age > 20 && student.Percentage >= 80
                    orderby student.Name
                    select student;
        // 3rd part -> execute the query
        foreach (var student in query)
        {
            Console.WriteLine(student.Name);
        }
    }
}

we can remove the 3rd part if we decide to by using immediate execution of query.

// immediate execution of query
List<Student> students = (from student in studentsList
                          where student.Age > 20 && student.Percentage >= 80
                          orderby student.Name
                          select student).ToList();

Another way to write queries

// another way to write queries
var queri = studentsList.
            Where(x => x.Age > 20 && x.Percentage >= 80).
            OrderBy(x => x.Name);

Conclusion

LINQ helps us with filtering, sorting and other operations by bringing SQL-like syntax to c#. This is an intro to LINQ and there are a lot more complex things you can do with it if you are interested feel free to explore the Microsoft docs -> Intro to LINQ

Thanks for reading 📖