Skip to content

Look back on linq

A long time ago, when I touched keywords like map/filter/reduce in Swift.

At that time, I generally called it Syntax Sugar. Today, I got a chance to continue digging into this concept as I am touching LINQ in C#.

Story begins⚓︎

My learning started from this fun pic:

image

After some investigation, I got this mapping from Swift to C#:

  • map -> Select -> projection -> SELECT (SQL)
  • filter -> Where -> selection -> WHERE
  • reduce -> Aggregate ->
  • Ordering (ORDER BY)?
  • Grouping (GROUP BY)?

Demurely⚓︎

Generally, this group of primitives (which means "the most basic building blocks in a programing language") come from Functional Programming. Being simple, functions are the blocks for the Functional Programming (FP) language.

Functional Programming Primitives⚓︎

This Underscore.js provides a general list of normal function primitives we can see in FPL. Of course, map/filter/reduce are part of it. Language like C# not only supports OOP (Object-Oriented Programming) features but also some FP syntax. This is where LINQ comes from.

To be or not to be⚓︎

When should we use LINQ, and when shouldn't we?

The answer can go back to FL. Taking video games as an example, when we need to manage thousands of states (player health, obstacles, character progression, etc.), it is easier to model this using objects, which hold state, instead of pure functions, which can not hold information.

So the conclusion is:

LINQ is better for data transformations:

  • Stateless, symmetric collection transformations (filter / map / sort / aggregate)

LINQ starts to break down (in this case, traditional for loop with if-else works safer and clearer):

  • Branching logic
  • Special cases
  • Order‑dependent behavior
  • Early decisions
  • Intermediate state that needs to be understood
  • Side effects

Reference⚓︎