I am a newer coder and am having a lot of issues creating the following lamdba expression dynamically using expression trees.
( x, y ) => DateTime.Compare( y.EFFECTIVE_DATE, x.EFFECTIVE_DATE )
I am just starting to understand the basics of the Expression Trees but don't seem to know enough to create this. I don't have any good code to really put here because honestly I am really fumbling around with this. Any help would be great.
Thank you in advance.
Sorry, first time posting and having some issues with formatting items.
So, In my main method I have the following:
var sortExpression = testing.GetExpression( "EFFECTIVE_DATE", "EFFECTIVE_DATE" );
if (e.SortDirection == SortDirection.Ascending)
{
paymentAuthorizationList.Sort( sortExpression );
}
And, in my Get Expression Method:
public Expression<Func<AuthorizePayments, AuthorizePayments, int >> GetExpression<t>( string propertyName, string propertyValue )
{
var paramX = Expression.Parameter( typeof( AuthorizePayments ), "x" ); // x
var paramY = Expression.Parameter( typeof( AuthorizePayments ), "y" ); // y
var xDate = Expression.Property( paramX, "EFFECTIVE_DATE" ); // x.EFFECTIVE_DATE
var yDate = Expression.Property( paramY, "EFFECTIVE_DATE" ); // y.EFFECTIVE_DATE
// DateTime.Compare(y.EFFECTIVE_DATE, x.EFFECTIVE_DATE)
var body = Expression.Call( typeof( DateTime ).GetMethod( "DateTime.Compare" ), yDate, xDate );
// (x, y) => DateTime.Compare(y.EFFECTIVE_DATE, x.EFFECTIVE_DATE)
var expr = Expression.Lambda<Func<AuthorizePayments, AuthorizePayments, int >>( body, paramX, paramY );
return expr; }
I know the variables are wrong at this time. The sort expression will not work for the sort method.
Am i just way off base for what I am trying to do?
Sorry for my ignorance and thanks for the help.
Well, you can "statically" create it with the compiler's help using a lambda expression:
Expression<Func<Foo, Foo, int>> expr =
(x, y) => DateTime.Compare(y.EFFECTIVE_DATE, x.EFFECTIVE_DATE);
If you'd like to do it "by hand":
var paramX = Expression.Parameter(typeof(Foo), "x"); // x
var paramY = Expression.Parameter(typeof(Foo), "y"); // y
var xDate = Expression.Property(paramX, "EFFECTIVE_DATE"); // x.EFFECTIVE_DATE
var yDate = Expression.Property(paramY, "EFFECTIVE_DATE"); // y.EFFECTIVE_DATE
// DateTime.Compare(y.EFFECTIVE_DATE, x.EFFECTIVE_DATE)
var body = Expression.Call(typeof(DateTime).GetMethod("Compare"), yDate, xDate);
// (x, y) => DateTime.Compare(y.EFFECTIVE_DATE, x.EFFECTIVE_DATE)
var expr = Expression.Lambda<Func<Foo, Foo, int>>(body, paramX, paramY);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With