【问题标题】:Add Contains to existing Func<T, object> property将包含添加到现有的 Func<T, object> 属性
【发布时间】:2017-03-05 05:17:08
【问题描述】:

我正在尝试为现有的 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 作为参数。

【问题讨论】:

    标签: c# linq properties where contains


    【解决方案1】:

    如果您只想将每个 Func&lt;T, object&gt; 转换为 Func&lt;T, bool&gt;,如果转换为字符串的第一个 func 返回对象包含 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 返回 tpye 一个对象,这不是最好的主意,如果您可以将其更改为您期望的真实类型,它将为您节省所有多余的转换。

    【讨论】:

    • 它有效,但我对 Linq Include 也有同样的问题。当我尝试使用 query = query.Include(x =&gt; include(x)); 其中 include 是 Func&lt;T, object&gt; 时出现错误:包含路径表达式必须引用导航在类型上定义的属性。
    • 您不能将此方法与 LINQ to Entities 一起使用来过滤 Include 方法中的项目,请参阅this 问题以获取替代方案。
    • 我的意思是别的。我想不是通过字符串而是通过 Func 将 Include 添加到我的查询中。无法通过对象做到这一点。
    • 我没有完全理解问题是什么以及您想要实现什么,我对您的最佳建议是通过a Minimal, Complete, and Verifiable example 提出一个新问题。
    • String.Contains 默认不区分大小写,使用扩展方法忽略大小写。
    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多