TypeScript common linq command equivalents / CheatSheet
Intro
Linq in c# is a great abstraction, it massively reduces the amount of code to do fairly basic operations, using TypeScript doesn’t mean you lose this functionality, its just a little different to achieve many of the operations. In this article I’ll run through the basic Linq-To-Object operations, and how you can achieve similar results in TypeScript.
For these examples, I’ll keep it simple with a list of Person objects that look like this:
(How good is that typescript constructor/field syntax!).
With the data:
- Chandler - Mr
- Monica - Mrs
- Rachel - Miss
- Joey - Mr
- Ross - Dr
Select
To select the names of each person with their title:
CSharp
Typescript
In TypeScript, the equivalent to select is the map function:
Where
To filter the list to only the people with the title “Mr”:
CSharp
Typescript
OrderBy
To order the list by Name:
CSharp
Typescript
In TypeScript, the equivalent to order by is the sort function, but you do have to give it a sort function that returns 1 or 0:
GroupBy
To group the list into the various titles:
CSharp
Typescript
There isn’t a simple equivalent to this, the closest thing is probably the reduce function:
FirstOrDefault
To select the first person with the title Mr, or null if none exist:
CSharp
Typescript
Aggregate
Lets concatenate all the names together:
CSharp
Typescript
This time, reduce is almost like for like with the c# equivalent