Skip to content
Menu
The Philosophy of Code
  • Home
  • About
  • Contact
The Philosophy of Code

Linq Cheat Sheet

Posted on October 9, 2020October 9, 2020

Linq lets us express collection transformations really nicely much of the time, but its names for operations are sometimes not the most obvious, so sometimes it helps me to write out the most common operations and what they mean as a cheat sheet. This is a list in order that I find them most common/useful:

Table of Contents

  • The Basics
    • Select
      • Examples
    • Where
      • Examples
    • First
      • Examples
      • FirstOrDefault
      • Single and SingleOrDefault
  • Advanced
    • SelectMany
      • Examples
    • Aggregate
      • Examples

The Basics

Select

Name(s) in other languages: map, transform, apply

What it does:

[a,b,c] -> [A,B,C]

Given an IEnumerable and a function for an item in that set, apply that function to each item to produce a new IEnumerable . Lazy.

Examples

//Converts each string to uppercase
(new[] {"left", "right", "up", "down"}).Select(s => s.ToUpper()); // Produces: ["LEFT", "RIGHT", "UP", "DOWN"]
//Squares a list of numbers
(new[] {1,2,3,4}).Select(number => number * number); // Produces: [1, 4, 9, 16]

Where

Name(s) in other languages: filter, remove-if, select

What it does:

[a,b,c] -> [a,c]

Given an IEnumerable and a function that takes an element and returns true or false, keep items where the function returns true.Lazy.

Examples

//Filter out odd numbers
(new[] {1,2,3,4}).Where(number => number % 2 == 0); // Produces: [2, 4]

First

Name(s) in other languages: head, front

What it does:

[a,b,c] -> a

Given an IEnumerable, return the first thing. Throws if the list is empty.

OR

Given an IEnumerable and a function that returns true or false, returns the first thing that that function returns true for. Throws if the list is empty or there are no matching elements.

Examples

//Get the first item
(new[] {1,2,3,4}).First(); // Produces: 1

//Fails if the list is empty
(new int[] {}).First(); // Throws an InvalidOperationException
//Gets the first even number
(new[] {1,2,3,4}).First(number => number % 2 == 0); // Produces: 2

FirstOrDefault

Like First, but returns the default value instead of throwing an exception.

Single and SingleOrDefault

Like First and FirstOrDefault, but throws if there is more than one item in the list, or more than one item that matches the predicate. Means “I expect this list only has one thing in it” or “I expect this list has exactly one of these things in it” respectively.

Advanced

SelectMany

Name(s) in other languages: flatten, join

What it does:

[ [a,b,c], [d,e,f], [g,h,i] ] -> [a,b,c,d,e,f,g,h,i]

Takes a “list of lists” and returns a single list containing all elements of every list.

Examples

var listOfLists = new[]
    {
        new[] {1, 2, 3},
        new[] {1, 2, 3},
    };
listOfLists.SelectMany(x => x); // Produces: [1,2,3,1,2,3]

Aggregate

Name(s) in other languages: fold, reduce, accumulate

What it does:

[a,b,c] -> A

Given a starting seed, visit each element in the list and apply each item to a value.

Aggregate seems really complicated at first, but once you use it a few times, it’s actually pretty easy and surprisingly useful.

Examples

var list = new[] {1, 2, 3};
//Sum the elements of list
list.Aggregate(0, (current, number) => current + number); //Produces: 6 (because 0+1+2+3 is 6)

 

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The benefits of being lazy

Jun 16, 2021

In programming, laziness can often be an asset. It has been said that it is a good trait for programmers themselves. It has to be a forward-thinking laziness, not a short term avoidance of work. Being methodical in the reduction of how much work you have to do via automation or streamlining of processes over…

Linq Cheat Sheet

Oct 09, 2020

Linq lets us express collection transformations really nicely much of the time, but its names for operations are sometimes not the most obvious, so sometimes it helps me to write out the most common operations and what they mean as a cheat sheet. This is a list in order that I find them most common/useful:…

yield, IEnumerator and the iterator pattern in C#

Aug 21, 2020

I have been programming in C# for around ten years now. Before that, I worked in C++. My education was games-focused and at the time, C++ was pretty much the only serious option for programming games. Some poor souls still insisted that C was still the better choice. I thought they were insane at the…

Archives

  • June 2021
  • October 2020
  • August 2020

RSS The Philosophy of Code

  • The benefits of being lazy
  • Linq Cheat Sheet
  • yield, IEnumerator and the iterator pattern in C#
©2023 The Philosophy of Code | Powered by SuperbThemes & WordPress