I have created this method to simulate SQL's IN operator:

public static IEnumerable<TSource> In<TSource, TMember>(this IEnumerable<TSource> source,
            Func<TSource, TMember> identifier, params TMember[] values) =>
         source.Where(m => values.Contains(identifier(m)));

to use it like:

var selectedAccounts = allAccounts.In(x => x.Id, 1, 2, 100); //select accounts whose Id's are 1, 2, 100

I think there's no problem with it since it's working on the in-memory data.

and this is the IQueryable version of it:

    public static IQueryable<TSource> In<TSource, TMember>(this IQueryable<TSource> source,
   Expression<Func<TSource, TMember>> identifier, params TMember[] values)
            var parameter = Expression.Parameter(typeof(TSource), "m");
            var inExpression = GetExpression(parameter, identifier, values);
            var theExpression = Expression.Lambda<Func<TSource, bool>>(inExpression, parameter);
            return source.Where(theExpression);

  static Expression GetExpression<TSource, TMember>(ParameterExpression parameter, Expression<Func<TSource, TMember>> identifier, IEnumerable<TMember> values)
            var memberName = (identifier.Body as MemberExpression).Member.Name;
            var member = Expression.Property(parameter, memberName);
            var valuesConstant = Expression.Constant(values.ToList());
            MethodInfo method = typeof(List<TMember>).GetMethod("Contains");
            Expression call = Expression.Call(valuesConstant, method, member);
            return call;

I'd like to know if this is how IQueryable methods are implemented? did I use the Expressions API right? and is there a better suggestion than using Reflection, or it's OK?

  • \$\begingroup\$ I have created this method - to do what? You need to explain what you did in more words. \$\endgroup\$ – t3chb0t Mar 14 '18 at 7:27
  • \$\begingroup\$ amended the question \$\endgroup\$ – mshwf Mar 14 '18 at 7:33
  • \$\begingroup\$ If you look at the C# Reference Source for Queryable you'll see they use an interesting compile time generic method named GetMethodInfo to retrieve the appropriate method. \$\endgroup\$ – NetMage Apr 2 '18 at 21:45

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.