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

Yan Cui

I help clients go faster for less using serverless technologies.

.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. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


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 *