Monday, March 9, 2015

Group by order

Quite a common case - assume we have a collection of items and we want to iterate over it, but at first by items with some feature, then by items without such feature.

For instance, we have list of integers and want to iterate firstly all even numbers, then all odd numbers.

First approach is to group items by this feature and then iterate over group:

var ints = new[]{1,2,3,4,5};

var groups = ints.ToLookup(x=>x%2==0);

var result = groups[true].Concat(groups[false]);

foreach (var i in result){
    // ..
}



But there is a trick - a boolean value is comparable, false < true, so instead of creating lookups and concatenating we can simply order the collection by feature descendingly:

var ints = new[]{1,2,3,4,5};

var result = ints.OrderByDescending(x=>x%2==0);

foreach (var i in result){
    // ..
}