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 aList<T>, which makes elements unique for you. You can then decide whether or not to add an element by anif.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:
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.Containson anISetwith (more or less) logarithmic rather than linear effort (might speed up your program measurably, depending on the number of elements).DISTINCTto make elements unique if suitable. However, this requires you to refactor the query.