表达式树嵌套了

时间:2012-05-08 14:19:57

标签: c# linq tree expression

我正在尝试动态构建一个表达式树,使用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]'不能用于返回类型'System.Boolean'

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

我假设您想要的是一个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)));
相关问题