Method I Wish Was There: DataGridView.GetDisplayIndexToPropertyNameMap

Alright, I’ll admit it, this one is rather obscure and only useful if you are doing strange things with a Windows Forms DataGridView.

I like this method because I think its a good use of Fold… err.. I mean Aggregate. I’m convinced Aggregate is an underutilized method so far by .NET developers.

In this case I like it because I can state what I want to do in a single statement rather than multiple statements.

public static IDictionary<int, string> GetDisplayIndexToPropertyNameMap(this DataGridView datagridview)
{
  var boundColumns = 
          datagridview.Columns.Cast<DataGridViewColumn>().Where(c => null != c.DataPropertyName);
  return boundColumns.Aggregate(
                new Dictionary<int, string>(),
                (a, b) => a.Insert(b.DisplayIndex, b.DataPropertyName));
   }

Notice the use of yesterday’s Dictionary.Insert so that we return the Dictionary at every iteration of the Aggregate*.

I find this MUCH more readable than if the Aggregate statement had been

return boundColumns.Aggregate(new Dictionary<int,string>(),
   (a,b) => { a.Add(b.DisplayIndex, b.DataPropertyName); return a; } );

The curly braces for the block lambda syntax and the return statement inside them really take away from the readability IMO.

* Note that this is why I put Insert explicitly on Dictionary instead of IDictionary. C# 3’s type inference is not good enough to figure out that we would want the signature of Aggregate to be IDictionary<int,string> instead of Dictionary<int,string> if Insert returned an IDictionary