Friday, November 19, 2010

Commutativity and LINQ

Yet another stupid questions. Imagine, you have defined a class:

class Entity{
 public int Id { get; set; }
 public int Priority { get; set; }
}

And also you have some sequence of Entity objects (i.e. IEnumerable entities). You need to group entities by its Id and select only entities with priority greater than 5.

As far as "and" is commutative and according to the task the following two blocks of code should return the same result


var group1 = entities.Where(e=>e.Priority > 5).GroupBy(e=>e.Id);
and
var group2 = entities.GroupBy(e=>e.Id).Select(g=>g.Where(e=>e.Priority > 5));

But this is wrong. There are two different sets of input data that will produce to different results (by two different reasons). Could you find them out?

Monday, November 1, 2010

Why IEnumerator<T> is IDisposable

Recently I've posted that IEnumerator<T> is IDisposable, but had not explained, why it is.

The explanation is rather simple - because of "yield return". Let's track this down.