Skip to content
Justin edited this page Apr 12, 2020 · 2 revisions

Language Integrated Queries ("LINQ") is a set of language features and extension methods in System.Linq designed to query over collections and operate on their elements, or more correctly, any type which implements IEnumerable<T> (a sequence).

sequence - Any type which implements IEnumerable<T>, an object which can be iterated over with foreach

element - Any object in a sequence

Getting Started Example

LINQ can often replace a loop, reducing program complexity in the process.

To use LINQ, System.Linq must be referenced by your program. Here's a short example to shows usage of one of LINQ's fundamental methods, Where(). Not to worry if you don't quite understand what you see here yet.

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

namespace LinqExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = new[] { 1, 2, 4, 9, 16, 25, 36 };

            // defines a sequence using LINQ
            IEnumerable<int> numbersOver24 = values
                .Where(x => x > 24); 

            // forces the sequence to execute
            // contains { 25, 36 }
            int[] numbersOver24Array = numbersOver24.ToArray();
        }
    }
}

This example shows one more import concept in LINQ, deferred executed. Sequences created by LINQ are generally not executed until they must. LINQ methods which force execution will be noted in the examples.

Method Chaining

TODO

Where(Predicate<T, bool>)

Filters a sequence based on the predicate passed into Where().

predicate - A function that accepts an element as the input argument, and returns true or false

Elements are in the resulting output sequence if the predicate returns true.

Example Use Case

You have a requirement to implement a program that returns all even numbered integers in a sequence.

Imperative Implementation

IEnumerable<int> GetEvenNumbers(IEnumerable<int> sequence)
{
    var list = new List<int>(); 
        
    foreach (var number in sequence)
    {
        if (number % 2 == 0)
        {
            list.Add(number); 
        }
    }

    return list;
}

LINQ Implementation

IEnumerable<int> GetEvenNumbers(IEnumerable<int> sequence)
{
    return sequence.Where(x => x % 2 == 0);
}

Select(Func<TSource, TResult> selector)

Transforms each element of the sequence to a new type, using the selector function passed in.

Example Use Case

You need to implement converting a day-of-week code (M - Monday, T - Tuesday, etc.) to a enum, DayOfWeek.

enum DayOfWeek
{
    Monday,
    Tuesday, 
    Wednesday,
    Thursday,
    Friday, 
    Saturday,
    Sunday,
    Unknown
}

Imperative Implementation

IEnumerable<DayOfWeek> ConvertToDaysOfWeek(string codes)
{
    var daysOfWeek = new List<DayOfWeek>();

    foreach (var dayCode in codes)
    {
        var valid = DaysOfWeekMap.TryGetValue(dayCode, out var dayOfWeek);
        daysOfWeek.Add(valid ? dayOfWeek : DayOfWeek.Unknown);
    }

    return daysOfWeek;
}

LINQ Implementation

IEnumerable<DayOfWeek> ConvertToDaysOfWeek(string codes)
{
    DayOfWeek Convert(char code)
    {
        var valid = DaysOfWeekMap.TryGetValue(code, out var dayOfWeek);
        return valid ? dayOfWeek : DayOfWeek.Unknown;
    }

    return codes.Select(Convert);
}

Other LINQ Methods

TODO

Clone this wiki locally