I query a two tables from a database and add unique values to a generic list.

If there is a value that I do not want to add to the list, how can I prevent the item from being added?

using (myOledbConn = new OleDbConnection(connAccessLrProduct))
        {
            List<string> lst = new List<string>();
            myOledbConn.Open();
            OleDbCommand cmd = myOledbConn.CreateCommand();
            cmd.CommandText = @"SELECT tblProducts.CODE, tblSubject.SUBJECT, tblProducts.GenSubject
                               FROM tblSubject INNER JOIN tblProducts ON tblSubject.ID = tblProducts.SubjectID
                               WHERE [SUBJECT] = 'Arts' or [SUBJECT] = 'Aged Care';";


            OleDbDataReader dbReader = cmd.ExecuteReader();
            while (dbReader.Read())
            {
                string generalSublject;
                string subject = (string)dbReader["SUBJECT"];
                if (lst.Where(t => t == subject).Count() == 0)
                    lst.Add(subject);
                if (dbReader["GenSubject"] != DBNull.Value)
                {
                    generalSublject = (string)dbReader["GenSubject"];
                    if(generalSublject.Equals("No related topics"))
                    {
                        //how do I exclude this item from being added to the list?
                    }
                    if (lst.Where(t => t == generalSublject).Count() == 0)
                        lst.Add(generalSublject);
有帮助吗?

解决方案

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 are SortedSet (tree based) and HashSet (hash based) - does not guarantee a particular order of the elements, but it does guarantee they're unique.
  • You can do a Contains on an ISet 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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top