Exploring LINQ in C#

Hello, C# enthusiasts! Today, we’ll dive into LINQ (Language Integrated Query), one of the most powerful features in C#. LINQ provides a convenient syntax for querying various data sources, including collections, databases, and XML. Let’s unravel what LINQ is and how to effectively use it in your C# applications.

What is LINQ?

LINQ is a set of methods and language features that allow you to work with data in a more readable and maintainable way. It integrates query capabilities directly into the C# language, enabling you to write queries using a syntax similar to SQL, directly in your C# code.

The Basics of LINQ

LINQ can be used with any IEnumerable or IQueryable data source. LINQ queries can be expressed in two main syntaxes:

  1. Method Syntax: Using method calls on `IEnumerable` or `IQueryable` collections.
  2. Query Syntax: Using a SQL-like syntax to express queries.

Using LINQ with Collections

Let’s start with some examples using LINQ with collections like arrays or lists.

Example Using Query Syntax

Here’s how to use LINQ to query a list of integers, selecting even numbers:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var evenNumbers = from n in numbers
                          where n % 2 == 0
                          select n;

        Console.WriteLine("Even Numbers:");
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

In this example, we define a list of integers and use LINQ’s query syntax to filter out even numbers from the list. The result is printed to the console.

Example Using Method Syntax

Now, let’s achieve the same result using method syntax:

public class Program
{
    public static void Main()
    {
        List numbers = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        var evenNumbers = numbers.Where(n => n % 2 == 0);

        Console.WriteLine("Even Numbers:");
        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

In the method syntax, we use lambda expressions to specify the condition directly within the Where method.

LINQ to Objects

LINQ to Objects refers to querying in-memory collections. You can use LINQ to filter, project, sort, and aggregate collections. Here’s an example that demonstrates sorting and projecting a collection:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        List products = new List
        {
            new Product { Id = 1, Name = "Laptop", Price = 999.99M },
            new Product { Id = 2, Name = "Tablet", Price = 499.99M },
            new Product { Id = 3, Name = "Smartphone", Price = 299.99M }
        };

        var sortedProducts = from p in products
                             orderby p.Price descending
                             select new { p.Name, p.Price };

        Console.WriteLine("Products sorted by price:");
        foreach (var product in sortedProducts)
        {
            Console.WriteLine($"Name: {product.Name}, Price: {product.Price}");
        }
    }
}

In this snippet, we created a simple Product class and a list of products. We then used LINQ to sort them by price in descending order and selected only the name and price to display.

LINQ with XML

LINQ can also be used to query and manipulate XML data. Here’s a brief example:

using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        string xmlData = @"
            
                
                    Laptop
                    999.99
                
                
                    Tablet
                    499.99
                
            ";

        XElement products = XElement.Parse(xmlData);
        var productNames = from p in products.Descendants("product")
                           select p.Element("name")?.Value;

        Console.WriteLine("Product Names:");
        foreach (var name in productNames)
        {
            Console.WriteLine(name);
        }
    }
}

In this example, we parsed a simple XML string and used LINQ to retrieve the names of the products.

Conclusion

LINQ is an incredibly powerful feature in C# that simplifies data manipulation and querying. Whether working with collections, databases, or XML, mastering LINQ can significantly improve the readability and maintainability of your code.

To learn more about ITER Academy, visit our website. Visit Here

Scroll to Top