Quantcast
Channel: User mykhailovskyi - Stack Overflow
Viewing all articles
Browse latest Browse all 29

Generic predicate to implement searching by any string property

$
0
0

Is there possibility to apply searching by any string property of entity? I need to build predicate to use it in LINQ query to database.

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: here is working code:

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;
}

Hope it would be helpful for someone.


Viewing all articles
Browse latest Browse all 29

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>