Skip to content

Instantly share code, notes, and snippets.

@takeshik
Created August 11, 2012 04:32
Show Gist options
  • Save takeshik/3320921 to your computer and use it in GitHub Desktop.
Save takeshik/3320921 to your computer and use it in GitHub Desktop.
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