|
Querying some data where each item may or may not have the same set of fields really throws off the WPF DataGrid . As it binds each row it throws and catches an exception every time it can't find a field entry. This is SLOOOOOOOW for a sparsley normal (if that's a term) data set.
Normalizing the data get's around all these possible exceptions at the expensive of determining the union of all fields and iterating over all of the data filling in the gaps.
public static IEnumerable<IDictionary<TKey, TValue>> Normalize<TKey, TValue>(
this IEnumerable<IDictionary<TKey, TValue>> rows)
{
return rows.Normalize<TKey, TValue>(EqualityComparer<TKey>.Default);
}
public static IEnumerable<IDictionary<TKey, TValue>> Normalize<TKey, TValue>(
this IEnumerable<IDictionary<TKey, TValue>> rows,
IEqualityComparer<TKey> comparer)
{
Debug.Assert(rows != null);
IEnumerable<TKey> columns = rows.SelectMany(d => d.Keys).Distinct(comparer);
List<IDictionary<TKey, TValue>> list = new List<IDictionary<TKey, TValue>>();
foreach (IDictionary<TKey, TValue> row in rows)
{
foreach (TKey column in columns.Where(column => row.ContainsKey(column) == false))
row.Add(column, default(TValue));
list.Add(row);
}
return list;
}
10 PRINT Software is hard. - D Knuth
20 GOTO 10
|
|
|
|