Photo by Baher Khairy on Unsplash
I will cover methods for getting subset of sequence.
Here are the methods covered so far.
- Part 1 〰️ Select, Aggregate, Where, OrderBy (Ascending, Descending)
- Part 2 〰️ Any, Distinct, Concat, SelectMany
- Part 3 〰️ Reverse, Zip, Min/Max
- Part 4 〰️ Union, Intersect, Except
- Part 5 〰️ Sum, Average, Count
- Part 6 〰️ First, Last, DefaultIfEmpty, Skip, Take
- Part 7 〰️ Empty, Repeat, Range
🔴 Overview
In this article, I will cover following methods.
LINQ Methods | Go to example |
---|---|
First/FirstOrDefault | First/FirstOrDefault |
Last/LastOrDefault | Last/LastOrDefault |
DefaultIfEmpty | DefaultIfEmpty |
Skip/SkipWhile | Skip/SkipWhile |
Take/TakeWhile | Take/TakeWhile |
The sample collections used in this part are shown as below.
C#
JavaScript
🔴 Examples
🔸 First/FirstOrDefault
Results
I’ve just used “first” in JavaScript to implement “First/FirstOrDefault”.
JavaScript is dynamically typed so it wouldn’t know what default value is unless you specify unlike in C#.
🔸 Last/LastOrDefault
Results
Same as “first”, I used “last” in JavaScript to implement both “Last/LastOrDefault”
🔸 DefaultIfEmpty
Results
In JavaScript, filter
returns an array of size 0 if no record is returned.
So I am checking for the size and return nullOrder
if the length is 0.
🔸 Skip/SkipWhile
Results
The callback in Array.prototype.filter also has an access to current index being process.
So the implementation for skip
simply filters out records below the given count
while skipWhile
filters out records that do not match the predicate.
🔸 Take/TakeWhile
Results
Take is the opposite of skip
so the boolean conditions are reversed.
🔴 Closing Remark
JavaScript is dynamically typed so returning a “default” value is tricky as a variable type is defined upon initialization. I’ve skipped implementing “*OrDefault” methods for that reason.
Please let me know should you find any errors or improvements I can make to the codes.
The full source code and instructions on how to run them are on GitHub.