[英]Exclusing Items to be added to a List
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. 我建议您使用
ISet<T>
而不是List<T>
,它使元素对您而言是唯一的。 You can then decide whether or not to add an element by an if
. 然后,可以通过
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:
但是有一些含义:
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 . ISet
典型的实现是SortedSet
(基于树)和HashSet
(基于哈希)-不保证元素的特定顺序 ,但可以保证它们是唯一的 。 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). ISet
进行“ Contains
”(根据元素数,可以显着提高程序速度)。 DISTINCT
to make elements unique if suitable. DISTINCT
来使元素唯一。 However, this requires you to refactor the query.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.