2012-08-07 82 views
2

我想在使用選中列表框的Winforms應用程序中過濾顯示的文檔,這樣當選擇2個標籤時,只有包含這些標籤的文檔纔會顯示出來,第三個標籤被選中。我正在使用實體框架。這是我擁有的,但我認爲它可能效率不高。我不喜歡我必須經常查詢數據庫。有什麼想法嗎?通過選定的標籤過濾文件列表

List<int> docIds = null; 
     if (tags != null) 
     { 
      docIds.AddRange(from di in frmFocus._context.AllocateDocumentTags 
          where di.tagId == tags[0] 
          select di.documentId); 
      for (int i = 1; i < tags.Length; i++) 
      { 
       List<int> docList = (from dId in frmFocus._context.AllocateDocumentTags 
            where dId.tagId == tags[i] 
            select dId.documentId).ToList(); 
       foreach (int n in docIds) 
       { 
        if (!docList.Contains(n)) 
        { 
         docIds.Remove(n); 
        } 
       } 
      } 

     } 

現在我想顯示基於ID的文檔,但...這裏的新代碼

docIds = (from di in frmFocus._context.AllocateDocumentTags.Distinct() 
            where tags.Contains(di.tagId) 
            select di.documentId).ToList(); 
       tagManagment.fillUsed(docIds); 
      } 
      ObjectSet<Documents> _docs = (from d in frmFocus._context.Documents 
        where docIds.Contains(d.id) 
        select d); 

回答

2

可以基本上只是做一個包含標籤:

List<int> docIds = (from di in frmFocus._context.AllocateDocumentTags 
        where tags.Contains(di.tagId) 
        select di.documentId); 

對於JOIN:

ObjectSet<Documents> _docs = (from doc in docIds 
           join d in frmFocus._context.Documents.ToList() on doc equals d.id 
           select d); 
+0

難道它不是「where tags.Contains(di.tagId)」嗎? – 2012-08-07 13:52:26

+0

@The_Cthulhu_Kid是的,對不起。更新! – Willem 2012-08-07 13:56:14

+0

不,這很好,我只是想確定一下。非常感謝你。這更簡潔! – 2012-08-07 13:58:57