Created
August 11, 2012 04:32
-
-
Save takeshik/3320921 to your computer and use it in GitHub Desktop.
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; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
new [] {"foo", "", "bar", null, "baz", " "} | |
.Where(Invert<Func<String, Boolean>>(String.IsNullOrWhiteSpace)) | |
// ~~~~~~~~~~~~~~~~~~~~~~~ (>_< | |
// .IsSequenceEqual(new [] { "foo", "bar", "baz", }) | |
.ToList() | |
.ForEach(Console.WriteLine); | |
} | |
public static TDelegate Invert<TDelegate>(TDelegate predicate) | |
{ | |
if (predicate.GetType().GetMethod("Invoke").ReturnType != typeof(Boolean)) | |
{ | |
throw new ArgumentException("predicate"); | |
} | |
var parameters = predicate | |
.GetType() | |
.GetMethod("Invoke") | |
.GetParameters() | |
.Select(p => Expression.Parameter(p.ParameterType, p.Name)) | |
.ToArray(); | |
return Expression.Lambda<TDelegate>( | |
Expression.Not( | |
Expression.Invoke(Expression.Constant(predicate), parameters) | |
), | |
parameters | |
).Compile(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment