8 Types of LINQ Query in C#: Unique Capabilities and Advantages

LINQ (Language Integrated Query) stands as a basic and powerful tool for data manipulation and querying. Understanding LINQ is essential for any developer who wants to write efficient and expressive code. This article covers different ways to work with LINQ query in CSharp (C#) for both beginners and advanced programmers with the aim of being comprehensive.

image 5

What is LINQ?

LINQ is like a special tool introduced in C# 3.0 that allows developers to query and modify data using a uniform syntax. It smoothly integrates query functionalities into the C#, offering a consistent and powerful approach to handle different data sources like collections, databases, XML, and others. LINQ brings several advantages, such as clearer code, faster development, and better data querying abilities.

There are several ways to work with LINQ in C#, each offering unique capabilities and advantages. Here are some common approaches:

  1. LINQ to Objects: Querying in-memory objects using LINQ syntax or extension methods (IEnumerable<T> or IQueryable<T> Collection).
  2. LINQ to SQL: Querying relational databases using LINQ syntax with ORM tools like Entity Framework or LINQ to SQL.
  3. LINQ to XML: Querying and modifying XML data using LINQ syntax with XDocument, XElement, and related classes.
  4. LINQ to Entities: Querying data from entity data models using LINQ syntax with Entity Framework.
  5. LINQ to Dataset: Querying data from ADO.NET datasets using LINQ syntax.
  6. LINQ to JSON: Querying and modifying JSON data using LINQ syntax with libraries like Newtonsoft.Json.
  7. Parallel LINQ (PLINQ): Performing parallel queries and operations on data using LINQ syntax with PLINQ.
  8. LINQ with Entity Framework Core: Querying and manipulating data using LINQ syntax with Entity Framework Core for lightweight and cross-platform data access.

Working with LINQ query in C#

1. LINQ to Objects

Basic Information: LINQ to Objects allows querying in-memory objects using LINQ syntax or extension methods. (IEnumerable<T> or IQueryable<T> Collection)

// Sample data
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// LINQ query to filter even numbers
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

// Displaying results
foreach (var num in evenNumbers)
{
    Console.WriteLine(num);
}

Example Explanation: In the above example, we have a list of numbers (List<int> numbers) and use LINQ query syntax to filter out even numbers (where num % 2 == 0). We then iterate over the result and display each even number.

2. LINQ to SQL (Entity Framework)

Basic Information: LINQ to SQL allows querying relational databases using LINQ syntax with ORM tools like Entity Framework or LINQ to SQL.

// Entity Framework DbContext
using (var dbContext = new YourDbContext())
{
    // LINQ query to retrieve data
    var employees = from emp in dbContext.Employees
                    where emp.Department == "IT"
                    select emp;

    // Displaying results
    foreach (var employee in employees)
    {
        Console.WriteLine($"Name: {employee.Name}, Department: {employee.Department}");
    }
}

Example Explanation: In this example, we used Entity Framework’s DbContext (YourDbContext) to query employees from the database where their department is “IT.”

3. LINQ to XML

Basic Information: LINQ to XML enables querying and modifying XML data using LINQ syntax with XDocument, XElement, and related classes.

XDocument doc = XDocument.Load("countryData.xml");

var countries = from country in doc.Descendants("Country")
                where country.Element("Population").Value > 100000000
                select country.Element("Name").Value;

Example Explanation: Here, we load XML data from a file (countryData.xml) and query countries with a population greater than 100,000,000.

4. LINQ to Entities (Entity Framework)

Basic Information: LINQ to Entities allows querying data from entity data models using LINQ syntax with Entity Framework. It is a full-featured ORM framework by Microsoft.

using (var dbContext = new YourDbContext())
{
    var employees = from emp in dbContext.Employees where emp.Department == "IT" select emp;
}

Example Explanation: Similar to LINQ to SQL, this example uses Entity Framework’s DbContext to query employees from the database where their department is “IT.”

5. LINQ to Dataset

Basic Information: LINQ to Dataset is used for querying data from ADO.NET datasets using LINQ syntax.

DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", connectionString);
adapter.Fill(dataSet, "Employees");

var employees = from DataRow row in dataSet.Tables["Employees"].Rows
                where row.Field<string>("Department") == "IT"
                select new
                {
                    Id = row.Field<int>("Id"),
                    Name = row.Field<string>("Name")
                };

Example Explanation: We define a dataset, fill it with data from a SQL query, and then query the dataset to select employees from the “IT” department.

6. LINQ to JSON (using Newtonsoft.Json)

Basic Information: LINQ to JSON is used for querying and modifying JSON data using LINQ syntax with libraries like Newtonsoft.Json.

string json = File.ReadAllText("data.json");
JArray array = JArray.Parse(json);

var products = from product in array
               where product["Price"].Value<decimal>() > 50
               select product["Name"].Value<string>();

Example Explanation: Here, we read JSON data from a file (data.json) and query products with a price greater than 50.

7. Parallel LINQ (PLINQ)

Basic Information: Parallel LINQ (PLINQ) allows performing parallel queries and operations on data using LINQ syntax.

List<int> numbers = Enumerable.Range(1, 1000).ToList();

var result = numbers.AsParallel().Where(num => num % 2 == 0).ToList();

Example Explanation: We generate a list of numbers and use PLINQ to perform a parallel query to filter out even numbers.

8. LINQ with Entity Framework Core

Basic Information: LINQ with Entity Framework Core is similar to LINQ with Entity Framework but is specifically tailored for lightweight and cross-platform data access with EF Core, which is a newer version of Entity Framework optimized for modern development scenarios.

// Your Entity Framework Core DbContext 
using (var dbContext = new YourDbContext())
{
    var employees = from emp in dbContext.Employees where emp.Department == "IT" select emp;
}

Example Explanation: This example is identical to LINQ to SQL and LINQ to Entities but uses Entity Framework Core for data querying.

Note: Here, you can checkout our post on Exception handling in C# Programming with Example

Grouping and Joining with LINQ

LINQ Grouping

LINQ offers powerful capabilities for grouping data, allowing developers to perform complex data operations with ease. Let’s explore this feature with example.

// Sample data
List<Product> products = GetProducts();

// LINQ query to group products by category
var groupedProducts = from prod in products
                      group prod by prod.Category into prodGroup
                      select new
                      {
                          Category = prodGroup.Key,
                          TotalProducts = prodGroup.Count()
                      };

// Displaying results
foreach (var group in groupedProducts)
{
    Console.WriteLine($"Category: {group.Category}, Total Products: {group.TotalProducts}");
}

Example Explanation: In this example, we grouped a list of products by their category, calculating the total number of products in each category.

LINQ Join Operations

LINQ offers capabilities for joining data, allowing developers to perform complex data operations and provides a new collection . Let’s explore with example.

// Sample data
List<Customer> customers = GetCustomers();
List<Order> orders = GetOrders();

// LINQ query to join customers and orders
var customerOrders = from cust in customers
                     join ord in orders on cust.CustomerId equals ord.CustomerId
                     select new
                     {
                         CustomerName = cust.Name,
                         OrderId = ord.OrderId,
                         OrderDate = ord.OrderDate
                     };

// Displaying results
foreach (var order in customerOrders)
{
    Console.WriteLine($"Customer: {order.CustomerName}, OrderId: {order.OrderId}, OrderDate: {order.OrderDate}");
}

Example Explanation: Here, we performed a join operation between customers and orders based on their customer IDs, creating a new collection that combines customer information with order details.

Conclusion

By following the steps outlined in this guide and practicing with the provided examples, you can enhance your C# programming skills and streamline your development workflows. Incorporate LINQ into your projects to write cleaner, more concise code and unlock the full potential of data handling in C#.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top