Monday, April 6, 2009

Pattern for Extension Methods?

The more extension methods I see and write the more I am starting to see a loose pattern forming. If I write an extension method for IQueryable then why not write something similar for IEnumerable. Sure the implementation is different, but from the outside they both feel similar. Take for instance Distinct; why only have that on IQueryable? I ended up writing my own, which was not a big deal, but byt the time I finished all the tests and a quick peer review I had spent almost a 4 hours. Not to metion the email & SharePoint entry to everyone else in the org announcing a new release of the our extensions dll. Not bad, but just distracting. Here is the code for anyone that is interested. Sorry about the formatting, this editor is pretty lame for code.

///
/// Takes a List of type and a function as the key selector
/// and returns a unique list of .
///

/// A class instance that uniquely identifies the current item. Strings work well.
/// The type of items in the target and return lists.
/// The input list. Not changed by this method.
/// The function that returns a KEY that uniquely identifies the current item
/// A list of where every item is unique by KEY
///
/// List<MyClass> aDistinctList = aTargetList.Distinct( i => i.Id);
///

///
///
/// Worth noting that there is a distinct method on the IQueryable<T>, but this does not work
/// on List<T>. This is an entirely different implementation form that method.
///

///
/// The order of the original list is maintained, only duplicats are removed.
///

///

public static List Distinct(this List pList, Func pGetUniqueKeyFunc)
{
if (pGetUniqueKeyFunc == null)
throw new ArgumentNullException("pGetUniqueKeyFunc");

if (pList == null pList.Count == 0)
return new List(0);

var aDistinctKeyHash = new Hashtable(); // the list of unique keys - used for lookup
var aDistinctItemList = new List();

// go thru each item in the source list and get the key for that item from the delegate
// if the key does not exist in the hashtable then add it to the hashtable and the item return list
// rinse - repeat...
foreach (var aItem in pList)
{
var aKey = pGetUniqueKeyFunc.Invoke(aItem);

if (!aDistinctKeyHash.ContainsKey(aKey))
{
aDistinctKeyHash.Add(aKey, aItem);
aDistinctItemList.Add(aItem);
}
}

return aDistinctItemList;
}

No comments:

Post a Comment