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);
}
}
Use a more appropriate tool for the job instead,
HashSet<string>.If you were to use
Containson the HashSet, it would be a more optimal solution than using it onList<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. TheAddmethod 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.