Introduction to LINQ in C# Programming


Language Integrated Query (LINQ) is a powerful feature in C# that allows you to query collections in a concise, readable, and efficient way. LINQ enables developers to write SQL-like queries directly in C# code to manipulate and retrieve data from arrays, lists, databases, and more.

Step 1: Understanding LINQ

LINQ provides a set of methods to query collections in C#. These methods are part of the System.Linq namespace. LINQ queries can be written in two syntaxes:

  • Query Syntax: Similar to SQL queries.
  • Method Syntax: Uses LINQ extension methods like Where, Select, OrderBy, etc.

We will explore both syntaxes in this tutorial.

Step 2: Using LINQ with Arrays

Let's start by querying an array using both query syntax and method syntax. Below is an example where we query an array of integers to find all numbers greater than 5.

Query Syntax Example


    using System;
    using System.Linq;
   namespace LINQExample
    {
        class Program
        {
            static void Main()
            {
                int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
               // Query syntax: Find numbers greater than 5
                var result = from num in numbers
                             where num > 5
                             select num;
               Console.WriteLine("Numbers greater than 5 (Query Syntax):");
                foreach (var num in result)
                {
                    Console.WriteLine(num);
                }
               Console.ReadLine();
            }
        }
    }
        

In this example, the LINQ query syntax is used to filter out the numbers greater than 5. The from keyword defines the data source, and the where clause specifies the condition.

Method Syntax Example


    using System;
    using System.Linq;
   namespace LINQExample
    {
        class Program
        {
            static void Main()
            {
                int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
               // Method syntax: Find numbers greater than 5
                var result = numbers.Where(num => num > 5);
               Console.WriteLine("Numbers greater than 5 (Method Syntax):");
                foreach (var num in result)
                {
                    Console.WriteLine(num);
                }
               Console.ReadLine();
            }
        }
    }
        

Here, the method syntax uses the Where method, which is a LINQ extension method that filters elements based on a condition. The lambda expression num => num > 5 defines the condition.

Step 3: Using LINQ to Sort Data

LINQ also allows sorting data. Below is an example where we use LINQ to sort an array of numbers in ascending order.

Query Syntax Example


    using System;
    using System.Linq;
   namespace LINQExample
    {
        class Program
        {
            static void Main()
            {
                int[] numbers = { 1, 9, 5, 3, 7, 8, 2, 6, 4 };
               // Query syntax: Sort numbers in ascending order
                var result = from num in numbers
                             orderby num
                             select num;
               Console.WriteLine("Numbers in ascending order (Query Syntax):");
                foreach (var num in result)
                {
                    Console.WriteLine(num);
                }
               Console.ReadLine();
            }
        }
    }
        

In the query syntax, the orderby clause sorts the numbers in ascending order. You can also use orderby descending for descending order.

Method Syntax Example


    using System;
    using System.Linq;
   namespace LINQExample
    {
        class Program
        {
            static void Main()
            {
                int[] numbers = { 1, 9, 5, 3, 7, 8, 2, 6, 4 };
               // Method syntax: Sort numbers in ascending order
                var result = numbers.OrderBy(num => num);
               Console.WriteLine("Numbers in ascending order (Method Syntax):");
                foreach (var num in result)
                {
                    Console.WriteLine(num);
                }
               Console.ReadLine();
            }
        }
    }
        

The method syntax example uses the OrderBy method to sort the array in ascending order. The lambda expression num => num specifies that we want to order the numbers themselves.

Step 4: Using LINQ with Collections

LINQ is not limited to arrays; you can also use LINQ with collections like List, Dictionary, etc. Below is an example of how to use LINQ to filter a list of objects.

Query Syntax Example with List


    using System;
    using System.Linq;
    using System.Collections.Generic;
   namespace LINQExample
    {
        class Program
        {
            class Person
            {
                public string Name { get; set; }
                public int Age { get; set; }
            }
           static void Main()
            {
                List people = new List
                {
                    new Person { Name = "John", Age = 25 },
                    new Person { Name = "Jane", Age = 30 },
                    new Person { Name = "Jake", Age = 35 },
                    new Person { Name = "Jill", Age = 40 }
                };
               // Query syntax: Find people older than 30
                var result = from person in people
                             where person.Age > 30
                             select person;
               Console.WriteLine("People older than 30 (Query Syntax):");
                foreach (var person in result)
                {
                    Console.WriteLine(person.Name + ", Age: " + person.Age);
                }
               Console.ReadLine();
            }
        }
    }
        

In this example, we use LINQ query syntax to filter a list of Person objects based on the age property. The result contains people older than 30.

Method Syntax Example with List


    using System;
    using System.Linq;
    using System.Collections.Generic;
   namespace LINQExample
    {
        class Program
        {
            class Person
            {
                public string Name { get; set; }
                public int Age { get; set; }
            }
           static void Main()
            {
                List people = new List
                {
                    new Person { Name = "John", Age = 25 },
                    new Person { Name = "Jane", Age = 30 },
                    new Person { Name = "Jake", Age = 35 },
                    new Person { Name = "Jill", Age = 40 }
                };
               // Method syntax: Find people older than 30
                var result = people.Where(person => person.Age > 30);
               Console.WriteLine("People older than 30 (Method Syntax):");
                foreach (var person in result)
                {
                    Console.WriteLine(person.Name + ", Age: " + person.Age);
                }
               Console.ReadLine();
            }
        }
    }
        

Here, we use method syntax with the Where method to filter out people older than 30 from the list of Person objects.

Step 5: Conclusion

LINQ in C# is an excellent tool for querying and manipulating data. It provides an easy-to-use, expressive, and readable way to work with collections. Whether you're working with arrays, lists, or complex data structures, LINQ makes data querying more intuitive. In this tutorial, we've seen how to use LINQ with query syntax and method syntax, as well as how to sort and filter data efficiently.




Advertisement