[英]list search in C#
我的C#網絡應用程序中有一個列表。 此列表填充有從數據庫獲取的關鍵字。 現在,我想在列表中搜索,因為我有多個關鍵字搜索。
如果某人輸入藍色,那么所有與藍色匹配的記錄都將被提取到列表中。 現在,當他輸入第二個關鍵字時,假設黃色,因此該列表應該被過濾,並且必須僅包含具有藍色和黃色且與第三個和第四個關鍵字相同的記錄。
這是代碼,我下一步要做什么?
public override List<ThumbNail> GetSearchResults(string search1, string path)
{
List<ThumbNail> mylist = new List<ThumbNail>();
if (search1.Length - 1 == search1.LastIndexOf(","))
search1 = search.Remove(search1.Length - 1);
List<string> search = new List<string>(search1.Split(','));
for(int i=0; i <search1.Count;i++)
{
OleDbCommand sqlcmdCommand1 =
new OleDbCommand("select Name,File,keyword from table1 where keyword like @searchone", mycon);
sqlcmdCommand1.Parameters.AddWithValue("searchone", search[i]);
sqlcmdCommand1.CommandType = CommandType.Text;
OleDbDataReader sdaResult = sqlcmdCommand1.ExecuteReader();
while (sdaResult.Read())
{
mytable thmb = new Thumbl();
thmb.Name = sdaResult.GetString(0);
thmbN.File = sdaResult.GetString(1);
thmb.keyword = sdaResult.IsDBNull(3) ? "" : sdaResult.GetString(6);
mylist.Add(thmb);
}
} sdaResult.Close();
return mylist;
}
public class Thumbnail
{
public int Id { get; set; }
public string Name { get; set; }
public string File { get; set; }
public string keyword { get; set; }
public string path { get; set; }
}
用戶輸入第一個關鍵字時執行此操作。 現在,當用戶鍵入第二個關鍵字時,所有與第一個關鍵字匹配的記錄都在mylist中,因此必須在與第一個關鍵字和第二個關鍵字匹配的列表上進行搜索,然后返回結果。
The DB table look like this:
id name keyword File Fkey
1 a yellow c:/ 20
2 a blue c:/ 20
3 a Pinky c:/ 20
4 b orange c:/ 21
5 b Redish c:/ 21
編輯 :更新您的問題后,我的答案不再適用,因為您的表結構與我預期的不同。 如果您的表格如下所示,我的答案將起作用:
id name keywords File
1 a yellow blue pinky c:/
2 b orange reddish c:/
老答案 :首先,您還需要選擇關鍵字,以便進行進一步的過濾。
thmb.Keywords = sdaResult.GetString(someIndex);
然后,您可以使用LINQ創建列表的過濾版本。
var filtered = mylist.Where(thmb => thmb.Keywords.Contains(search2));
...,您可以在輸入新的搜索關鍵字后立即進行進一步過濾。
var filtered = filtered.Where(thmb => thmb.Keywords.Contains(search3));
filtered
是IEnumerable
。 如果需要列表,請.ToList()
應用.ToList()
。
新答案 :基本上,您需要對表結構進行以下操作:
從數據庫中進行第二次提取,列出包含第二個關鍵字和
刪除第二個列表中未包含的第一個列表中的所有列表項。 例如,如果您的包含第二個關鍵字的名稱列表是一個名為narrowingSearch
搜索的List<string>
,那么您可以
var filteredList = mylist.Where(thmb => narrowingSearch.Contains(thmb.Name));
編輯 :現在,您已經有了一個通用的FK,您應該能夠通過使用更高級的SQL來做到這一點,類似於:
SELECT name, file
FROM table1
WHERE keyword like @search0
AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search1)
AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search2)
...
您可以像這樣在循環中構造此SQL:
string[] search = search1.Split(',');
OleDbCommand cmd = new OleDbCommand("SELECT name, file FROM table1 WHERE keyword LIKE @search0", mycon);
cmd.Parameters.AddWithValue("@search0", search[0]);
for (int i = 1; i < search.Length; i++) {
cmd.CommandText += " AND fk IN (SELECT fk FROM table1 WHERE keyword LIKE @search" + i.ToString() + ")";
cmd.Parameters.AddWithValue("@search" + i.ToString(), search[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.