Understanding and Using C# Query Expressions (LINQ): Data Querying Simplified

Learn how to use C#'s query expressions (LINQ) for efficient and readable data querying. This tutorial explains the syntax, common clauses (`from`, `where`, `orderby`, `select`), and demonstrates how to query various data sources, making data manipulation in C# more intuitive and efficient.



Understanding C# Query Expressions (LINQ)

C# query expressions provide a powerful and readable way to query data using LINQ (Language Integrated Query). They resemble SQL syntax, making them intuitive for those familiar with database querying.

Query Expression Structure

A query expression starts with the `from` clause and ends with a `select` or `group` clause. It consists of several clauses that specify the data source, filtering criteria, ordering, and the final result.


IEnumerable<int> evenNumbers = 
    from number in numbers //Data source
    where number % 2 == 0 //Filtering Condition
    select number; //Result

Iterating Through Query Results

Query expressions return an `IEnumerable` sequence. You can iterate through this sequence using:

  • IEnumerator.MoveNext() method
  • A `foreach` loop

Remember to include the `System.Linq` namespace using a `using` statement.

Example 1: Filtering an Array

This example uses a query expression to filter out odd numbers from an array:


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

public class QueryExample {
    public static void Main(string[] args) {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        IEnumerable<int> oddNumbers = from n in numbers where n % 2 != 0 select n;
        // ... (code to print the odd numbers) ...
    }
}

Example 2: Querying a Collection of Objects

This example retrieves student names from a list based on a specific ID:


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

// ... (Student class definition) ...

public class QueryExample {
    public static void Main(string[] args) {
        // ... (code to get students, query for names based on ID, and print names) ...
    }
}