ASP.Net MVCにDisplayNameFor(x=>x.Title)
ヘルパーがあります。私は同様の行動で何かを実装したい。
User
クラス( u=>u.Birthdate
またはu => u.Name)、オペランド(Greater、Less、Equal)とDateTime.Now
ような値に基づいて式を受け取り、式を返すメソッドを用意したいu=>u.Birthdate > DateTime.Now
私は作品から手動で結果の式を構築する必要があることを理解しています。私が頭を包むことができないことは、プロパティの表現を渡して処理することです。
編集:
次のようなメソッドを呼びたい
GetFilterPredicate(u=>u.Birthdate,FilterOps.GreaterThan,DateTime.Parse("01.01.2013")
または
GetFilterPredicate(u=>u.SomeIntProperty,FilterOps.Equals,2)
更新:私はこの質問の解決策とコレクションプロパティのフィルタリングhttps://github.com/Alexander-Taran/Lambda-Magic-Filtersを使ってレポを作成しました
これはあなたのニーズを満たしていますか?
[TestClass]
public class UnitTest1
{
public Expression<Predicate<T>> GetFilterPredicate<T, R>(Expression<Func<T, R>> selector, FilterOps operand, R value)
{
var parameter = selector.Parameters[0];
var left = selector.Body;
var right = Expression.Constant(value);
var binaryExpression = Expression.MakeBinary(operand.ToExpressionType(), left, right);
return Expression.Lambda<Predicate<T>>(binaryExpression, parameter);
}
[TestMethod]
public void TestMethod1()
{
var p1 = this.GetFilterPredicate((User u) => u.Birthday.TimeOfDay.Hours, FilterOps.LessThan, 12);
var p2 = this.GetFilterPredicate((User u) => u.Size, FilterOps.Equal, 180);
var user = new User() { Birthday = new DateTime(2000, 1, 1), Size = 180 };
Assert.IsTrue(p1.Compile()(user));
Assert.IsTrue(p2.Compile()(user));
}
}
public enum FilterOps
{
GreaterThan, LessThan, Equal
}
public static class MyExtensions
{
public static ExpressionType ToExpressionType(this FilterOps operand)
{
switch (operand)
{
case FilterOps.GreaterThan: return ExpressionType.GreaterThan;
case FilterOps.LessThan: return ExpressionType.LessThan;
case FilterOps.Equal: return ExpressionType.Equal;
default: throw new NotSupportedException();
}
}
}
public class User { public DateTime Birthday { get; set; } public int Size { get; set; } }
私はこれがあなたが目指しているものだと信じています。
public Func<User, bool> MyMethod<TProperty>(Expression<Func<User, TProperty>> func, ComparisonPredicate op, TProperty value)
{
}
public enum ComparisonPredicate
{
Equal,
Unequal,
LessThan,
LessThanOrEqualTo,
GreaterThan,
GreaterThanOrEqualTo
}