0

Does a List have a property or mechanism by which I can prevent duplicate entries from being added to it, or do I have to search the list for it each time?

IOW, it would be much nicer just to go:

List<String> AAppsToDisplay = new List<String>();
AAppsToDisplay.DuplicatesAllowed = false;
...
while (odr.Read()) 
{
  AAppsToDisplay.Add(odr.GetString(0)); 
}

than to have to do this:

List<String> AAppsToDisplay = new List<String>();
. . .
String s = String.Empty;
while (odr.Read()) 
{
  s = odr.GetString(0);
  if (! AAppsToDisplay.Contains(s))
  {
    AAppsToDisplay.Add(s);  
  }
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

3 Answers3

15

Use a more appropriate tool for the job instead, HashSet<string>.

var hashset = new HashSet<string>();

// in loop
hashset.Add(value);

If you were to use Contains on the HashSet, it would be a more optimal solution than using it on List<string>, particularly if the set grew particularly large. However, if it is permissible within your business requirement to silently discard duplicates, then you do not need to. The Add method returns a boolean indicating if the value was added. Duplicates never make it into the set.


It is important to note that HashSet<T> is not documented to preserve insertion order. You may observe results in the same order of insertion, and that may be impacted by your particular usage, but you should not rely upon it.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
1

You could use an extension method to the List class:

public static class StringListExtensions {
    public static bool AddIfNotPresent(this List<string> list, string newString) {
        if (!list.Contains(newString)) {
            this.Add(newString);
            return true;
        }
        return false;
    }
}
Paul Grimshaw
  • 19,894
  • 6
  • 40
  • 59
1

You could use System.Linq library and go

List<String> AAppsToDisplay = new List<String>();
...
while (odr.Read()) 
{
  AAppsToDisplay.Add(odr.GetString(0)); 
}

//new code
AAppsToDisplay = AAppsToDisplay.Distinct().ToList();
m.t.bennett
  • 1,290
  • 16
  • 34