2012-08-07 68 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