← Back to all articles

Filtering by information in previous elements

I've been off work sick for the last 2 days so I thought I'd catch up on some blogging. It's been a couple of weeks as I've been busy reading the Haskell language specification. There is obviously a close relationship between F# and Haskell, but its becoming increasing clear to me that many of the C# 2.0 & 3.0 language features were inspired by Haskell (Erik Meijer's influence I suppose) & its predecessors.

I'll have some posts on what I'm learning shortly, but for now, back to LINQ!

So we have a stream of notifications, some of which are related to each other.

new[]
{
    new { Id = 42, Parent = 0 },
    new { Id = 100, Parent = 38 },
    new { Id = 101, Parent = 42 },
    new { Id = 102, Parent = 37 },
    new { Id = 103, Parent = 101 },
    new { Id = 104, Parent = 85 },
    new { Id = 105, Parent = 95 },
    new { Id = 106, Parent = 103 },
}

The desired output is;

42
101
103
106

I've found you can easily do this in Rx by combining Scan & DistinctUntilChanged.

new[]
{
    new { Id = 42, Parent = 0 },
    new { Id = 100, Parent = 38 },
    new { Id = 101, Parent = 42 },
    new { Id = 102, Parent = 37 },
    new { Id = 103, Parent = 101 },
    new { Id = 104, Parent = 85 },
    new { Id = 105, Parent = 95 },
    new { Id = 106, Parent = 103 },
}
.ToObservable()
.Scan(0, (acc, item) => item.Parent == acc ? item.Id : acc)
.DistinctUntilChanged()

Unfortunately the Enumerable extensions are missing DistinctUntilChanged. I'll ask if it can be added to the next release.

Cheers,
James

Comments