gpt4 book ai didi

c# - 仅当来自比较可枚举的所有(非原始)值都包含在目标可枚举中时才返回结果的查询

转载 作者:行者123 更新时间:2023-11-30 17:12:04 28 4
gpt4 key购买 nike

我们有一个类型为 Unit 的实体集合、一个类型为 UnitProp 的实体集合和一个类型为 Prop 的实体集合像这样定义(简化):

class Unit
{
int ID;
ICollection<UnitProp> UnitProps;
}

class UnitProp
{
int ID;
int UnitID;
Unit Unit;
int PropID;
Prop Prop;
}

class Prop
{
int ID;
string Description;
}

我们有一个包含Prop(称为RequiredProps)的List,我们需要用它来查询集合。我们想要返回满足在 RequiredProps 中指定所有 Prop 的条件的 Unit 集合。

我这样写查询:

var result = ctx.Units
.Where(x => RequiredProps.AsEnumerable()
.Except(x.UnitProps.Select(y => y.Prop))
.Count() == 0)
.ToList();

当然,这是 Linq to Entities,因此查询会抛出异常:无法创建“Prop”类型的常量值。在此上下文中仅支持基本类型(“例如 Int32、String 和 Guid”)。

我也试过这个:

var result = ctx.Units
.Where(x => RequiredProps.Select(y => y.ID)
.Except(x.UnitProps
.Select(y => y.Prop)
.Select(y => y.ID))
.Count() == 0)
.ToList();

...但它产生了相同的异常。

建议?

最佳答案

var requiredIds = RequiredProps.Select(y => y.ID);

var result = ctx.Units
.Where(m => !requiredIds
.Except(m.UnitProps.Select(x => x.Prop.ID)))
.Any())
.ToList();

关于c# - 仅当来自比较可枚举的所有(非原始)值都包含在目标可枚举中时才返回结果的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032928/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com