gpt4 book ai didi

c# - 表达式树嵌套 wheres

转载 作者:太空宇宙 更新时间:2023-11-03 16:32:01 26 4
gpt4 key购买 nike

我正在尝试动态构建一个表达式树,它使用 in 查询有效地查询数据源。我要复制的查询是

Countries.Where(y => Countries
.Where(x =>
x.CountryLanguage.Any(b => b.CountryID == 73) &&
x.CountryLanguage.Any(b => b.CountryID == 150))
.Select(z => z.ShortCode)
.Contains(y.ShortCode))

我已经尝试了很多方法来做到这一点,但这是我最近的尝试:

public void AddContainsWhereClause(IQueryable<T> objectSet, string predicateIdentifier)
{
ParameterExpression pe = Expression.Parameter(typeof(T), predicateIdentifier);

Expression expInner = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { typeof(T) },
objectSet.Expression,
Expression.Lambda<Func<T, bool>>(rootExperession, resultExpression));

Expression expOuter = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { typeof(T) },
objectSet.Expression,
Expression.Lambda<Func<T, bool>>(expInner, pe));

}

NB rootExpression 是:

x => x.CountryLanguage.Any(b => b.CountryID == 73) &&
x.CountryLanguage.Any(b => b.CountryID == 150)

但这会返回:

[ApplicationFramework.LINQBuilder.tests.Country]' cannot be used for return type 'System.Boolean'

谁知道我做错了什么?

最佳答案

我假设您想要的是一个 lambda 函数来模拟 Where 的谓词组件打电话。

where 子句的类型必须是 Func<TSource, bool> , 但你调用 Queryable.Where ,实际上返回一个 IEnumerable .

相反,沿着表达式树路径(这可能非常复杂且难以维护)进行下去,您真正的问题是否只是您需要选择一个支持所提供国家/地区列表语言的国家/地区列表?

int[] requiredCountryIds = {73, 150};

// Select countries which contain all required country IDs in their CountryLanguage set
var resultSet =
countries.Where(
y => requiredCountryIds.All(requiredCountryId => y.CountryLanguage.Any(b => b.CountryId == requiredCountryId)));

关于c# - 表达式树嵌套 wheres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500466/

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