Posted in:

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

Comment by Thomas Levesque

I have something similar in my Linq.Extras library, but it's a little more generic than RunLengthEncode since it returns IGroupings. It can be used like this:

 
var next = "13112221"
.GroupUntilChanged()
.Select(g => $"{g.Count()}{g.Key}")
.ToDelimitedString("");



The library also contains similar methods, like
- GroupUntilChangedBy
- DistinctUntilChanged (inspired by Observable.DistinctUntilChanged in Reactive Extensions)
- DistinctUntilChangedBy

Thomas Levesque
Comment by Mark Heath

Cool, I hand't come across your library. MoreLINQ also has a more generic GroupAdjacent method which works similarly to your GroupUntilChanged method

Mark Heath