Exploring MoreLINQ Part 12 - Run Length Encoding
The twelfth video in my Exploring MoreLINQ series looks at the RunLengthEncode
extension method. It is I suppose a bit more of an obscure offering, but there might be times when you need to count adjacent matching elements in a sequence.
For example, in one of the Advent of Code problems I solved a while back, I needed to calculate the next element in the "look and say" number sequence. RunLengthEncode
would be ideal for this. Here's how you'd use it to calculate the next look and say number after 13112221
:
var next = "13112221"
.RunLengthEncode()
.Select(g => $"{g.Value}{g.Key}")
.ToDelimitedString("");
You can find all videos in this series here.
Want to learn more about LINQ? Be sure to check out my Pluralsight course LINQ Best Practices.
Comments
I have something similar in my Linq.Extras library, but it's a little more generic than
RunLengthEncode
since it returnsIGrouping
s. It can be used like this:The library also contains similar methods, like
-
GroupUntilChangedBy
-
DistinctUntilChanged
(inspired by Observable.DistinctUntilChanged in Reactive Extensions)-
DistinctUntilChangedBy
Thomas LevesqueCool, I hand't come across your library. MoreLINQ also has a more generic GroupAdjacent method which works similarly to your GroupUntilChanged method
Mark Heath