添加包含到现有 Func<T, object> 属性

Add Contains to existing Func<T, object> property

我正在尝试为现有的 Func 属性列表创建 Contains 子句,但我不知道如何将其附加到之前传递的属性列表。

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> properties, string queryPhrase)
    {
        var whereClauses = new List<Func<T, bool>>();

        foreach (var property in properties)
        {
            /// how to add Contains to existing property Func<T, object> ?
            whereClauses.Add(property.Contains(queryPhrase));
        }

        return whereClauses;
    }

如何添加?我尝试使用一些 Expression.Call 但它没有将 Func 作为参数。

如果您只是想将每个 Func<T, object> 转换为 Func<T, bool>,如果转换为字符串的第一个 func return 对象包含 queryPhrase,您可以这样做:

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    var whereClauses = new List<Func<T, bool>>();
    foreach (var func in funcs)
    {
        whereClauses.Add(o => func(o).ToString().Contains(queryPhrase));
    }
    return whereClauses;
}

或使用 LINQ 更好:

 public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    return funcs.Select(func => new Func<T, bool>(o => func(o).ToString().Contains(queryPhrase)).ToList();
}

如果 reutrn 对象实际上是一个列表而不是字符串,您可以用类似的方式检查 queryPhrase 是否是列表的一部分:

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    return funcs.Select(func => new Func<T, bool>(o => ((List<string>)func(o)).Contains(queryPhrase)).ToList();
}

让你的 func return 成为一个对象并不是最好的主意,如果你能把它改成你期望的真实类型,它会省去所有多余的转换。