Advertisement

01.13.2008 at 05:15PM PST, ID: 23079765
[x]
Attachment Details

C# Use generics to remove duplicates from a lists of different types

Asked by sapbucket in C# Programming Language, Programming Languages, .NET

Tags: duplicates, remove, list, generic, from

Hello experts,

 I am trying to remove duplicates from strongly typed lists. For example, I use the following to remove duplicates from List<string> objects:

        public static List<string> RemoveDuplicateSections(List<string> sections)
        {
            Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
            List<string> finalList = new List<string>();
            int i = 0;
            foreach (string currValue in sections)
            {
                if (!uniqueStore.ContainsKey(currValue))
                {
                    uniqueStore.Add(currValue, 0);
                    finalList.Add(sections[i]);
                }
                i++;
            }
            return finalList;
        }

However, I have six strongly typed list objects (List<car>, List<truck>, <List<semi>, List<van>, List<suv>, List<racer>) that I need to remove duplicates from, and they all implement INamedObject:

    public interface INamedObject
    {
        string Name { get; set; }
    }

For example:

    public class racer : INamedObject
    {
        private string _name = "";
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

and to create a list of racer's I would do the following:

List<racer> racers = new List<racer>();
racer r = new racer();
racers.Add(r);
...etc.

How can I write a generic removeDuplicates() method that will operate on any of the six lists? My current solution requires six different methods (six different method signatures). But the code for each method is nearly identical! There must be a way to eliminate the duplication. I am thinking generics will be the soluton.

Much thanks,
sapbucket
Start Free Trial
[+][-]01.13.2008 at 05:36PM PST, ID: 20650161

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]01.14.2008 at 01:40AM PST, ID: 20651927

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: C# Programming Language, Programming Languages, .NET
Tags: duplicates, remove, list, generic, from
Sign Up Now!
Solution Provided By: PockyMaster
Participating Experts: 2
Solution Grade: A
 
 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628