If your LINQ provider supports basic filtering but doesn't support Contains() (looking at you WCF Data Services), here's a workaround
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Linq.Expressions; | |
static class Program { | |
static Expression<Func<T, bool>> In<T, R>(this Expression<Func<T, R>> member, params R[] values) { | |
var prop = member.Body as MemberExpression; | |
if (prop == null) | |
throw new Exception("Expression has to be member"); | |
if (values.Length == 0) | |
return _ => true; | |
var body = values.Select(v => Expression.Equal(prop, Expression.Constant(v))).Aggregate(Expression.OrElse); | |
return Expression.Lambda<Func<T, bool>>(body, member.Parameters[0]); | |
} | |
// Helps with type inference | |
static Expression<Func<A, B>> E<A, B>(Expression<Func<A, B>> exp) { | |
return exp; | |
} | |
class SomeModel { | |
public string Id { get; set; } | |
} | |
static void Main(string[] args) { | |
var values = new[] { "value1", "value2" }; | |
var exp = E((SomeModel x) => x.Id).In(values); | |
Console.WriteLine(exp); // x => ((x.Id == "value1") OrElse x.Id == "value2")) | |
} | |
} |
Nice, but one suggestion:
if (values.Length == 0) return _ => true;
should be changed to
if (values.Length == 0) return _ => false;
I think it makes logical sense for the expressions to return false since the value can never be contained in an empty collection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Equivalent F# : http://fssnip.net/ks