c# - 通过两个属性从 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
我想通过两个属性从这个列表中排除另一个类型列表-CmsFileId
和DocumentType
,所以我尝试编写一些代码,例如:
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()
仅支持原始类型。
解决方案
我首先要说你的结论是完全错误的,你在评论中提到的错误消息要么不存在,要么与完全不同的东西有关。这是一个小提琴,显示您的代码编译时没有任何问题:https ://dotnetfiddle.net/Aor3rH
但是,您可能应该知道,即使它确实可以编译,代码的质量也非常低,因为您正在执行一种O(n^2)
算法来实现您的排除(差异)操作,而不是O(nlogn)
您应该能够轻松完成的操作。此外,这个特定的算法是morelinq
名称下的 nuget 包的一部分ExceptBy
,因此您甚至不需要正确实现它,只需引用它并使用它!
推荐阅读
- scala - 带增量编号的加特林进料器(非随机)
- c# - .NetCore 将带有数组的 JSON 对象绑定到字典
- sql - 如何从最大日期小于表 A 中的日期的表 B 中获取值
- c++ - 如何初始化对象中的静态指针数组
- c# - Active Directory / LDPA 未使用长用户名进行身份验证
- go - 如何使用 client-go 在 Pod 的容器中执行多个命令?
- python - 使用循环写入目录中的每个文件
- microsoft-teams - 我可以用一个命令呼叫团队中的所有成员吗
- api - 用于确定照片是从照片还是真人中单击的 Api
- android - 应用程序关闭后 RoomDatabase 对象上的 Android NullPointerException