Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate string from List (.NET 2.0!)

Tags:

c++

c#

.net

list

I'm having issues finding the most efficient way to remove duplicates from a list of strings (List).

My current implementation is a dual foreach loop checking the instance count of each object being only 1, otherwise removing the second.

I know there are MANY other questions out there, but they all the best solutions require above .net 2.0, which is the current build environment I'm working in. (GM and Chrysler are very resistant to changes ... :) )

This limits the possible results by not allowing any LINQ, or HashSets.

The code I'm using is Visual C++, but a C# solution will work just fine as well.

Thanks!

like image 565
greggorob64 Avatar asked Aug 26 '09 15:08

greggorob64


2 Answers

This probably isn't what you're looking for, but if you have control over this, the most efficient way would be to not add them in the first place...

Do you have control over this? If so, all you'd need to do is a myList.Contains(currentItem) call before you add the item and you're set

like image 96
John Avatar answered Oct 07 '22 22:10

John


You could do the following.

List<string> list = GetTheList();
Dictionary<string,object> map = new Dictionary<string,object>();
int i = 0;
while ( i < list.Count ) {
  string current = list[i];
  if ( map.ContainsKey(current) ) {
    list.RemoveAt(i);
  } else {
    i++;
    map.Add(current,null);
  }
}

This has the overhead of building a Dictionary<TKey,TValue> object which will duplicate the list of unique values in the list. But it's fairly efficient speed wise.

like image 35
JaredPar Avatar answered Oct 07 '22 21:10

JaredPar