I'd suggest you to use a ISet<T>
instead of a List<T>
, which makes elements unique for you. You can then decide whether or not to add an element by an if
.
var mySet = new SortedSet<string>();
while(dbReader.Read())
{
if(dbReader["GenSubject"] != DBNull.Value)
{
var generalSubject = (string)dbReader["GenSubject"];
if(!generalSublject.Equals("No related topics"))
{
mySet.Add(generalSubject); // returns false if already in Set
}
else
{
// do nothing
}
}
Did this help you and answer your question? I hope I got you right and helped you with a simplified version of the code that focuses on the problem only. It has a few implications though:
- An
ISet
- typical implementations areSortedSet
(tree based) andHashSet
(hash based) - does not guarantee a particular order of the elements, but it does guarantee they're unique. - You can do a
Contains
on anISet
with (more or less) logarithmic rather than linear effort (might speed up your program measurably, depending on the number of elements). - You might also go for an SQL
DISTINCT
to make elements unique if suitable. However, this requires you to refactor the query.