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

.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

.Net Tips – Use LINQ to create pairs of adjacent elements from a collection

Suppose you have an array of numbers, say, [1, 3, 5, 7, 9, …], and you want to pair each element up with its neighbour in the array, e.g. [[1, 3], [3, 5], [5, 7], [7, 9], …].

Sure, you can iterate through the indices of the elements and recursively grab the element at an index and its neighbour:

   1: // an array of odd numbers

   2: var arr = new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };


   4: // standard imperative way, iterate through the indices and grab

   5: // the elements from the arrays

   6: var arrPairs = new List<int[]>();

   7: for (var i = 0; i < arr.Length - 1; i++)

   8: {

   9:     arrPairs.Add(new[] { arr[i], arr[i+1] });

  10: }

OR, you can use LINQ and the Zip method added in .Net 4 and do this instead:

   1: var arrPairsLinq = arr.Skip(1).Zip(arr, (second, first) => new[] { first, second }).ToArray();

A much more elegant solution, no? ;-)

.Net Tips – Use LINQ to avoid nested loops

Admit it, we’ve all done it before, writing those nasty nested loops just so we can iterate through multiple lists to get some combination/permutation of the lists, e.g.:

   1: for (int i = 0; i < 10; i++)

   2: {

   3:     for (int j = 0; j < 10; j++)

   4:     {

   5:         for (int k = 0; k < 10; k++)

   6:         {

   7:             // do something

   8:         }

   9:     }

  10: }

This code obviously works and well understood amongst developers, but it’s not very readable and trying to terminate the outer loops from the inner loops is a pain and requires you to use one or more boolean flags which you need to track on every iteration at potentially every level of your loop…

A better way to solve this common problem is to use LINQ to ‘flatten’ the nested loops into a single loop:

   1: var triplets = from I in Enumerable.Range(0, 10)

   2:                from J in Enumerable.Range(0, 10)

   3:                from K in Enumerable.Range(0, 10)

   4:                select new { I, J, K };


   6: foreach (var triplet in triplets)

   7: {

   8:     // do something

   9: }

Sweet, right? :-)

Converting List<T> using covariance

I saw an interesting use of covariance today, consider an interface IMyClass and an implementing class MyClass:

   1: public interface IMyClass { }


   3: public class MyClass : IMyClass { }

If you want to convert an List<MyClass> to a List<IMyClass> you would normally use the Enumerable.Cast method but did you know that you can also use C# 4’s support for covariance in the type parameter and do this instead:

   1: var original = new List<MyClass>();


   3: var converted = original.ToList<IMyClass>()

Funky, eh? ;-)

Though I think it’s a party trick best avoided for any production code, for which you should still prefer:

   1: var converted = original.Cast<IMyClass>().ToList();


  • it achieves the same result
  • it is just as expressive
  • it is the standard way of doing this kind of conversions in LINQ
  • it is understood by most C# developers so unlikely to cause confusion

There’s another argument for using Cast, in the case of use-defined implicit/explicit operators. Imagine if you have another class which does not inherit from MyClass but defines an explicit operator which allows you to cast an instance of MyClass:

   1: public class MyOtherClass

   2: {

   3:     public static explicit operator MyClass(MyOtherClass other)

   4:     {

   5:         return new MyClass();

   6:     }

   7: }

In cases like this, you won’t be able to use the covariance trick:

   1: void Main()

   2: {

   3:     var original = new List<MyClass>();


   5:     Console.WriteLine(original.GetType());                               // List<MyClass>


   7:     // cast here doesn't actually do anything

   8:     Console.WriteLine(original.Cast<IMyClass>().ToList().GetType());     // List<IMyClass>


  10:     // changes the compile type, works because of covariance

  11:     Console.WriteLine(original.ToList<IMyClass>().GetType());            // List<IMyClass>


  13:     // casts the objs to MyOtherClass using the defined convertor

  14:     Console.WriteLine(original.Cast<MyOtherClass>().ToList().GetType()); // List<MyOtherClass>


  16:     // this line won't compile.

  17:     // it doesn't work because this is not covariance, there's no inheritance

  18:     // relationship between MyClass and MyOtherClass

  19:     // Console.WriteLine(objs.ToList<MyOtherClass>().GetType());

  20: }


StackOverflow question – Casting List<T> – covariance/contravariance problem

IList<T> doesn’t extend IList

Looking at these two images snapped right off MSDN, what do you notice?






that IEnumerable<T> extends IEnumerable but IList<T> doesn’t extend IList!?

I know, peculiar isn’t it?


Turns out, it was for a good reason:

"A sequence of integers can be treated as a sequence of objects, by boxing every integer as it comes out of the sequence. But a read-write list of integers cannot be treated as a read-write list of objects, because you can put a string into a read-write list of objects. An IList<T> is not required to fulfill the whole contract of IList, so it does not inherit from it."