通用谓词,用于实现任何字符串属性的搜索

时间:2015-03-23 16:40:34

标签: c# .net linq

是否有可能通过实体的任何字符串属性应用搜索?我需要构建谓词以在LINQ查询到数据库中使用它。

var stringPropertyNames = typeof(T)
            .GetProperties()
            .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
            .Select(pi => pi.Name);

foreach (var item in stringPropertyNames)
{
    // here some code to build Predicate corresponding to sql LIKE statement
}

UPD: 这是工作代码:

public static IEnumerable<T> ContainsInAnyString<T>(IQueryable<T> collection, string query)
{
    var stringPropertyNames = typeof(T)
        .GetProperties()
        .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
        .Select(pi => pi.Name);

    var item = Expression.Parameter(typeof(T), "item");
    var searchArgument = Expression.Constant(query);
    var method = typeof(string).GetMethod("Contains", new[] { typeof(string) });

    foreach (var name in stringPropertyNames)
    {
        var currentProp = Expression.Property(item, name);
        var startsWithDishExpr = Expression.Call(currentProp, method, searchArgument);
        var lambda = Expression.Lambda<Func<T, bool>>(startsWithDishExpr, item);
        collection = collection.Where(lambda);
    }

    return collection;
}

希望对某人有所帮助。

1 个答案:

答案 0 :(得分:3)

这真的很简单:

var entityParameter = Expression.Parameter(typeof(T), "entity");

return 
 Expression.Lambda<Func<T, bool>>
 (
   Expression.Equal
   (
     Expression.MakeMemberAccess(entityParameter, propertyInfo),
     Expression.Constant(valueToSearchBy)
   ),
   entityParameter
 );

当然,这是A == B。如果您想要A like '%' + B + '%',则必须将Expression.Equal更改为string.Contains。我会把它留作练习,因为你还没有展示你的任何作品:)