You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

表达式树:如何检查列表元素是否满足指定条件?

问题内容

我正在使用Expression<Func<T, object?>> DatabaseProjection定义从T中提取的值,示例场景中会得到字符串或整数类型的对象列表:

DatabaseProjection = p => p.Voyages.SelectMany(v => v.Passages.Select(p => p.Location.Name))

需要传入某个值,检查提取出的列表中是否存在满足指定条件的元素。条件由以下方法生成:

private static Expression GetExpression
    (ConditionType conditionType, InvocationExpression invokedProjection, ConstantExpression value) => conditionType switch
    {
        ConditionType.Is => Expression.Equal(invokedProjection, value),
        _ => throw new NotImplementedException($"{conditionType} is not supported."),
    };

以下是本应针对列表构建表达式的方法:

public static Expression CreateExpression(Condition condition, Expression projection, ParameterExpression parameter)
{
    var invokedProjection = Expression.Invoke(projection, parameter);

    //ConstantExpression value;
    if (invokedProjection.Type.GetInterfaces().Contains(typeof(IList)))
    {
        var containsMethod = typeof(IList).GetMethod("Contains", new Type[] { typeof(IList) });

        var genericType = invokedProjection.Type.GetTypeInfo().GetGenericArguments().First();
        var castValue = string.IsNullOrWhiteSpace(condition.Value) && genericType.IsValueType
            ? Activator.CreateInstance(genericType)
            : Convert.ChangeType(condition.Value, genericType);

        var value = Expression.Constant(castValue, genericType);

        var contExp = Expression.Call(containsMethod!, invokedProjection, GetExpression(condition.Type, **invokedProjection**, value));

        return Expression.Constant(false);
    }
}

我知道不能将invokedProjection传入GetExpression方法,因为无法将字符串类型的value与字符串列表进行比较。我需要实现类似LINQ的逻辑:

list.Any(el => el.Name == name)

条件的内部逻辑已在GetExpression中实现,但不知道如何遍历列表,为每个元素检查条件。以下是CreateExpression方法的调用代码:

private static Expression CreateFilterExpression(Alert alert, ParameterExpression parameter, Func<string, Expression> createProjection)
{
    var conditionExpression = ExpressionFactory.CreateExpression(condition, projectionExpression, parameter);
        return expression;
}

附invokedExpression示意图:
存储获取名称列表表达式的invokedExpression

内容的提问来源于stack exchange,提问作者Michal Szura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:22:49