Dynamic create predicate using a projection selector and projected value RRS feed

  • Question

  • Hi,

    I am trying to dynamic create the "Where" clause for Linq-to-SQL based on a function that will select the entity's property and the input value.

            public static IQueryable<T> Where<T, Tout>(this IQueryable<T> query, Func<T, Tout> selector, Tout value) where T : class
                Expression<Func<T, bool>> predicate = t => selector(t).Equals(value);
                if (predicate != null) query = query.Where(predicate);
                return query;

    I have search high and low and found solutions that uses PredicateBuilder. However I only have a selector function and not a predicate function.

    Is there a way to create the predicate dynamically for Linq-to-SQL?

    Friday, July 13, 2012 10:35 AM

All replies

  • Hi skywang,

    I guess you should go through the following thread which has a similar scenario like this, hope this could help you:

    Best Regards,

    Tony Xiao [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, July 17, 2012 7:48 AM
  • Hi Tony,

    My problem is slightly different. I explain further. For example I have this POCO

    public class SomeEntity
      public int PropertyOne { get; set; }
      public string PropertyTwo { get; set; }

    I want to do something like this :

    int propertyOneValue = 1; string propertyTwoValue = "SomeString";

    Expresssion<Func<SomeEntity, int>> userSuppliedSelectorOne = t=>t.PropertyOne;

    Expression<Func<SomeEntity, string>> userSuppliedSelectorTwo = t=>t.PropertyTwo; var entitiesWithPropertyOneFiltered = db.SomeEntities.Where(userSuppliedSelectorOne, propertyOneValue ); var entitiesWithPropertyTwoFiltered = db.SomeEntities.Where(userSuppliedSelectorTwo, propertyTwoValue);

    I want to create the predicate dynamically from the selected property and the value. 

    Any help is appreciated. Thank you in advance.

    Friday, July 20, 2012 7:40 AM