views:

355

answers:

1

Hello all,

i search for a dynamic linq-to-sql Contains (StartsWith / EndsWith) method.

I’ve tried the following code, but it didn't work.

Any ideas?

public static IQueryable<T> WhereContains<T, V>(this IQueryable<T> queryable, string propertyName, V propertyValue)
{
    ParameterExpression pe = Expression.Parameter(typeof(T), "p");
    Expression left = Expression.Property(pe, propertyName);
    Expression right = Expression.Constant(propertyValue, typeof(V));

    IQueryable<T> x = queryable.Where<T>(
        Expression.Lambda<Func<T, bool>>(
            Expression.Call(
                typeof(T).GetMethod("Contains"),
                left,
                right),
            new ParameterExpression[] { pe }));

    return x;
}
+1  A: 

LINQ-to-SQL knows how to translate StartsWith, EndsWith and Contains for strings.

For example:

View.Customers = from c in db.Customers
                 where c.ContactName.EndsWith("c")
                 orderby c.CompanyName
                 select c;

Ref: http://davidhayden.com/blog/dave/archive/2007/11/23/LINQToSQLLIKEOperatorGeneratingLIKESQLServer.aspx

If you are trying to achieve a sort of Reflection style anything that has a Contains Method that takes two parameters, you're going to have a harder time...

Yannick M.