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(Li
st<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