LINQ OrderBy – using Comparer<T>.Create and F#’s Object Expressions

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

The real-time data platform that empowers developers to build innovative products faster and more reliably than ever before.

Learn more

.Net 4.5 introduced a handy little new method Comparer<T>.Create to aid the creation of bespoke comparers, which is great because it means that you don’t have to define a new Comparer class when it is going to be needed once.

In case you’re wondering, it’s still not possible to define anonymous implementation of interfaces in C#, but with Comparer<T>.Create you can at least create a bespoke instance of IComparer<T> from an anonymous method:

As a side, you can also apply the same technique for other single method interfaces yourself, for instance, if you were happy to ignore the existence of the Zip extension method for the sake of the example, you could define your own Zip extension method which takes in an instance of an IZipper<T, U, V>:

Whilst we’re on the topic of anonymous interface implementation. F# has a nice little feature call Object Expressions, it provides a mechanism for creating anonymous types that are based on existing base type, interface, or set of interfaces, and for the two examples, here’s how that solution might look in F#:

Notice that there’s no need for an explicit implementation class for IZipper<T, U, V> interface at all using Object Expressions and how much less code you end up writing with F#! So seriously, why aren’t you checking out F# already!? Winking smile

Whenever you’re ready, here are 4 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. Do you want to know how to test serverless architectures with a fast dev & test loop? Check out my latest course, Testing Serverless Architectures and learn the smart way to test serverless.
  3. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  4. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

1 thought on “LINQ OrderBy – using Comparer<T>.Create and F#’s Object Expressions”

  1. Pingback: F# Weekly #4, 2013 « Sergey Tihon's Blog

Leave a Comment

Your email address will not be published. Required fields are marked *