Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use reflection to create lambda expression like x => new { .. }

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

like image 583
Alex Avatar asked Jan 11 '13 09:01

Alex


People also ask

What does => mean in lambda?

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

How do you create a lambda function in C++?

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.


1 Answers

You can create Expressions 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();
like image 176
Nick Butler Avatar answered Oct 08 '22 06:10

Nick Butler