Using a Lambda to Dynamically Create an IComparer

Just recording the following for those lost coding souls like me who are trying to find a solution on the web :-)

I needed to instantiate a SortedSet for a WinRT application that I am writing. I didn’t want to create a new class that implements an IComparer (just being lazy). I thought that a simple lambda should suffice for the job at hand. After some digging, I found that .NET 4.5 that was just released, offers this capability.

var sorted = new SortedSet<Foo>(Comparer<Foo>.Create((x, y) => x.Bar.CompareTo(y.Bar)));

Hopefully this will help someone!

Comments are closed.