Generic function to removeDuplicates from Generic List

        //created based on http://www.kirupa.com/net/removingDuplicates2.htm

        //Why it is not in .Net Framework yet? Why HashSet<T> is only in Orcas(http://blogs.msdn.com/bclteam/archive/2006/11/09/introducing-hashset-t-kim-hamilton.aspx)

        public static List<GenericType> removeDuplicates<GenericType>(List<GenericType> inputList)

        {

            Dictionary<GenericType, int> uniqueStore = new Dictionary<GenericType, int>();

            List<GenericType> finalList = new List<GenericType>();

 

            foreach (GenericType currValue in inputList)

            {

                if (!uniqueStore.ContainsKey(currValue))

                {

                    uniqueStore.Add(currValue, 0);

                    finalList.Add(currValue);

                }

            }

            return finalList;

        }

 

Alternative solution is to use List.RemoveAll(Predicate<T>) -(misleading name for the function, that allow to remove only specified by Predicate)

 

posted @ Tuesday, September 11, 2007 3:42 PM
Print

Comments on this entry:

# re: Generic function to removeDuplicates from Generic List

Left by Michael Freidgeim at 7/26/2009 2:17 AM
Gravatar
In 3.5 the function is obsolete, use LINQ Distinct() instead

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«April»
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910