I have an IQuerable<object> source
object and have to get from it something like that (but using reflection).
source.Select(t => new SelectListItem { Name = t.Name, Value = t.Id })
How can I do that, or where can i find references of constructing that kind of expression tree.
Thanks
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.
Creating a Lambda Expression in C++auto greet = []() { // lambda function body }; Here, [] is called the lambda introducer which denotes the start of the lambda expression. () is called the parameter list which is similar to the () operator of a normal function.
You can create Expression
s using the System.Linq.Expressions
namespace ( MSDN )
In your case, it would look something like this:
var source = typeof( Source );
var target = typeof( SelectListItem );
var t = Expression.Parameter( source, "t" );
var sourceName = Expression.MakeMemberAccess( t, source.GetProperty( "Name" ) );
var sourceId = Expression.MakeMemberAccess( t, source.GetProperty( "Id" ) );
var assignName = Expression.Bind( target.GetProperty( "Name" ), sourceName );
var assignValue = Expression.Bind( target.GetProperty( "Value" ), sourceId );
var targetNew = Expression.New( target );
var init = Expression.MemberInit( targetNew, assignName, assignValue );
var lambda =
( Expression<Func<Source,SelectListItem>> ) Expression.Lambda( init, t );
The you could use it like this:
IQueryable<Source> list = ...
List<SelectListItem> items = list.Select( lambda ).ToList();
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