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);
4

1 回答 1

2

你基本上可以在标签上做一个包含:

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

对于加入:

ObjectSet<Documents> _docs = (from doc in docIds
                              join d in frmFocus._context.Documents.ToList()  on doc equals d.id
                              select d);
于 2012-08-07T13:48:50.163 回答