///
/// Takes a List of type
/// and returns a unique list of
///
///
///
/// The input list. Not changed by this method.
/// The function that returns a KEY that uniquely identifies the current item
///
///
///
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
{
if (pGetUniqueKeyFunc == null)
throw new ArgumentNullException("pGetUniqueKeyFunc");
if (pList == null pList.Count == 0)
return new List
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