首页 > 解决方案 > 通过两个属性从 IQueryable 中排除复杂对象列表

问题描述

我有两种类型:

public class DocumentEntityItem 
{
    public int Id { get; set; }
    public string Type { get; set; }
}

public partial class DocumentEntityToFilesCategory
{
    public int FilesCategoryId { get; set; }
    public int CmsFileId { get; set; }
    public Nullable<int> Sorder { get; set; }
    public string DocumentType { get; set; }

    public virtual FilesCategory FilesCategory { get; set; }
}

我得到了DocumentEntityToFilesCategory类型列表。DocumentEntityItem我想通过两个属性从这个列表中排除另一个类型列表-CmsFileIdDocumentType,所以我尝试编写一些代码,例如:

List<string> mainList  = new List<string>()
{
   "1/document",
   "1/link",
   "2/document",
   "3/link"
};
    var documentToCategoryItems= DB.DocumentEntityToFilesCategory.Where(z => z.FilesCategoryId == categoryId);
    List<DocumentEntityItem> documentEntityItems= mainList.Select(z => new DocumentEntityItem
    {
       Id = Int32.Parse(z.Split("/")[0]),
       Type = z.Split("/")[1]
    }).ToList();
    var toDelete = documentToCategoryItems.Where(z => !documentEntityItems.Any(c=>c.Id==z.CmsFileId&&c.Type==z.DocumentType));

但是,List.Any()仅支持原始类型。

标签: c#entity-frameworklinq

解决方案


我首先要说你的结论是完全错误的,你在评论中提到的错误消息要么不存在,要么与完全不同的东西有关。这是一个小提琴,显示您的代码编译时没有任何问题:https ://dotnetfiddle.net/Aor3rH

但是,您可能应该知道,即使它确实可以编译,代码的质量也非常低,因为您正在执行一种O(n^2)算法来实现您的排除(差异)操作,而不是O(nlogn)您应该能够轻松完成的操作。此外,这个特定的算法是morelinq名称下的 nuget 包的一部分ExceptBy,因此您甚至不需要正确实现它,只需引用它并使用它!


推荐阅读