Exploring LINQ with Arrays in C#

ยท

3 min read

In this article, we'll explore how to use Language Integrated Query (LINQ) with arrays in C#. LINQ provides a convenient and powerful way to perform queries on data collections such as arrays. Let's look at some common LINQ operations with an example array of integers.

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

class Program
{
    static void Main(string[] args)
    {
        // Sample array
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        // Filtering
        var evenNumbers = numbers.Where(n => n % 2 == 0);
        Console.WriteLine("Filtered (even) numbers:");
        PrintCollection(evenNumbers);

        // Projection
        var squares = numbers.Select(n => n * n);
        Console.WriteLine("\nSquares of numbers:");
        PrintCollection(squares);

        // Aggregation
        var sum = numbers.Sum();
        var max = numbers.Max();
        var min = numbers.Min();
        var average = numbers.Average();
        Console.WriteLine($"\nSum: {sum}, Max: {max}, Min: {min}, Average: {average}");

        // Sorting
        var sortedNumbersAsc = numbers.OrderBy(n => n);
        Console.WriteLine("\nSorted numbers (ascending):");
        PrintCollection(sortedNumbersAsc);

        var sortedNumbersDesc = numbers.OrderByDescending(n => n);
        Console.WriteLine("\nSorted numbers (descending):");
        PrintCollection(sortedNumbersDesc);

        // Element Operations
        var firstElement = numbers.First();
        var lastElement = numbers.Last();
        var singleElement = numbers.Single(n => n == 5);
        var elementAt = numbers.ElementAt(3);
        Console.WriteLine($"\nFirst: {firstElement}, Last: {lastElement}, Single: {singleElement}, ElementAt(3): {elementAt}");

        // Quantifiers
        var anyGreaterThan10 = numbers.Any(n => n > 10);
        var allGreaterThan0 = numbers.All(n => n > 0);
        var contains5 = numbers.Contains(5);
        Console.WriteLine($"\nAnyGreaterThan10: {anyGreaterThan10}, AllGreaterThan0: {allGreaterThan0}, Contains5: {contains5}");

        // Conversion
        var listFromNumbers = numbers.ToList();
        var arrayFromNumbers = numbers.ToArray();
        Console.WriteLine("\nConverted to List:");
        PrintCollection(listFromNumbers);
        Console.WriteLine("\nConverted to Array:");
        PrintCollection(arrayFromNumbers);
    }

    static void PrintCollection<T>(IEnumerable<T> collection)
    {
        foreach (var item in collection)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    }
}

Filtering

We use the Where method to filter the array and get even numbers:

var evenNumbers = numbers.Where(n => n % 2 == 0);

Projection

To project each element in the array to its square, we use the Select method:

var squares = numbers.Select(n => n * n);

Aggregation

LINQ provides several aggregation methods such as Sum, Max, Min, and Average:

var sum = numbers.Sum();
var max = numbers.Max();
var min = numbers.Min();
var average = numbers.Average();

Sorting

We can sort the array in ascending or descending order using OrderBy and OrderByDescending:

var sortedNumbersAsc = numbers.OrderBy(n => n);
var sortedNumbersDesc = numbers.OrderByDescending(n => n);

Element Operations

LINQ also allows us to perform element operations like First, Last, Single, and ElementAt:

var firstElement = numbers.First();
var lastElement = numbers.Last();
var singleElement = numbers.Single(n => n == 5);
var elementAt = numbers.ElementAt(3);

Quantifiers

Quantifiers like Any, All, and Contains help us to check conditions on the array elements:

var anyGreaterThan10 = numbers.Any(n => n > 10);
var allGreaterThan0 = numbers.All(n => n > 0);
var contains5 = numbers.Contains(5);

Conversion

Finally, we can convert the array to a list and vice versa:

var listFromNumbers = numbers.ToList();
var arrayFromNumbers = numbers.ToArray();

By using LINQ, we can simplify many common operations on arrays and make our code more readable and expressive.

ย