Note: The article is applied for .Net version > 3.5 and C# > 3.0.
In previous post we learnt basic understanding of Expression and few insights how Expression represents the code as data. Also we learned how to compile and invoke an Expression.
In this post you’ll learn,
- Creating a simple lambda expression.
- Creating a dynamic Linq expression.
Before moving ahead I want to mention the MSDN documentation of Expression class to go through for its methods and properties available to build code.
Creating a simple lambda expression
Let’s take a sample expression which adds up two numbers using a delegate.
Expression<Func<int, int, int>> sumExpr = (a, b) => a + b;
This is how we can write it in the code but it’s possible to build such expressions on the fly. The non-generic Expression class provides a lots of methods and properties.
If we parse this expression, (see previous article) we’ll get something like the following:
- Parameters = {a, b}
- Body = a + b
- NodeType = Lambda
- var paramExprA = Expression.Parameter(typeof(int), "a");
- var paramExprB = Expression.Parameter(typeof(int), "b");
- var body = BinaryExpression.Add(paramExprA, paramExprB);
- var lambda = Expression.Lambda<Func<int, int, int>>(body, paramExprA, paramExprB);
Now to execute it, we have to do the same as declared Expressions.

var result = lambda.Compile()(2, 3);

The method can be generalized with generics and then it can be called with any types:
- private static Expression < Func < T, T, T >> BuildIt < T > ()
- {
- var paramExprA = Expression.Parameter(typeof(T), "a");
- var paramExprB = Expression.Parameter(typeof(T), "b");
- var body = BinaryExpression.Add(paramExprA, paramExprB);
- var lambda = Expression.Lambda < Func < T,
- T, T >> (body, paramExprA, paramExprB);
- return lambda;
- }
var res = BuildIt<int>().Compile()(2, 3);
I hope you must be comfortable building the expressions, so let’s move on and build a little complex and useful expression which would help reducing the duplicate code.
Creating a simple dynamic Linq expression
Now we have a class ‘TestDemo’ and we want to convert the list of objects of `TestDemo` to another list of objects of class ‘SelectListItem’. This is a class in ASP.NET MVC which represents the items source of HTML Dropdownlist and its very common case. So assuming that we have 10-11 types of such classes like `TestDemo` which would get converted to Dropdownlist to show on view. In real scenario, let’s assume these classes are DbContext entities pulling data from DB and converting them to Dropdownlist compatible objects.
For multiple classes the LINQ would go like:
- MyDbContext db = new MyDbContext();
- List < SelectListItem > selectedItems = new List < SelectListItem > ();
- if (type == null) return selectedItems;
- if (type == typeof(TestDemo))
- selectedItems = db.TestDemo.Select(i => new SelectListItem
- {
- Text = i.Name, Value = i.Id.ToString()
- }).ToList();
- if (type == typeof(TestDemo1))
- selectedItems = db.TestDemo1.Select(i => new SelectListItem
- {
- Text = i.Name, Value = i.Id.ToString()
- }).ToList();
- if (type == typeof(TestDemo2))
- selectedItems = db.TestDemo2.Select(i => new SelectListItem
- {
- Text = i.Name, Value = i.Id.ToString()
- }).ToList();
- if (type == typeof(TestDemo3))
- selectedItems = db.TestDemo3.Select(i => new SelectListItem
- {
- Text = i.Name, Value = i.Id.ToString()
- }).ToList();
So the solution was to create a Generic method which can supply the expression and return the list of ‘SelectListItem’.
Let’s define the signature of the generic method,
public static IEnumerable<SelectListItem> GetList<T>(this IQueryable<T> source)
This is a generic Extension method for IQueryables so it can be invoked via any IQueryable type. And T is the Type of entity on which this will be invoked. In our case T will be TestDemo, TestDemo1 etc..
To start building the expression we will again break it down to it’s expression tree.
- i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() };
- Parameters = i
- Body = new SelectListItem { Text = i.Name, Value = i.Id.ToString() }
- NodeType = Lambda
- var paramExpr = Expression.Parameter(typeof(T), "i");
- Create a new object of SelectedListItem.
- Fill the properties of the object by parameter i.e. i
- Call ToString() method on i.Id property.
First we need information about the properties of both source and target classes which will get mapped during object creation. Below we have used Reflection to get the property info of both classes and create a map so that we can easily identify the mapping between properties.
- KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap1
- = new KeyValuePair<PropertyInfo, PropertyInfo>(
- // Text prop of selected item
- typeof(SelectListItem).GetProperty("Text"),
- // Name prop of T class
- typeof(T).GetProperty("Name"));
- KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap2
- = new KeyValuePair<PropertyInfo, PropertyInfo>(
- // Value prop of Selected Item
- typeof(SelectListItem).GetProperty("Value"),
- // Id prop from T class
- typeof(T).GetProperty("Id"));
- var propertyA = Expression.Property(paramExpr, sourceDestPropMap1.Value);
- var propertyB = Expression.Property(paramExpr, sourceDestPropMap2.Value);
- var propertyBToString = Expression.Call(propertyB, typeof(object).GetMethod("ToString"));
- var createObject = Expression.New(typeof(SelectListItem));
- var InitializePropertiesOnObject = Expression.MemberInit(
- createObject,
- new []
- {
- Expression.Bind(sourceDestPropMap1.Key, propertyA),
- Expression.Bind(sourceDestPropMap2.Key, propertyBToString)
- });
- var selectExpression = Expression.Lambda<Func<T, SelectListItem>>(InitializePropertiesOnObject, paramExpr);

Well looks good. Now all we have do is supply this express to Select and everything will be done by LINQ. Add below line to invoke the Expression on Select and return the List.
- return source.Select(selectExpression).ToList();
- public static class QueryableExtension
- {
- public static IEnumerable < SelectListItem > GetTable < T > (this IQueryable < T > source)
- {
- KeyValuePair < PropertyInfo, PropertyInfo > sourceDestPropMap1 = new KeyValuePair < PropertyInfo, PropertyInfo > (
- // Text prop of selected item
- typeof(SelectListItem).GetProperty("Text"),
- // Name prop of T class
- typeof(T).GetProperty("Name"));
- KeyValuePair < PropertyInfo, PropertyInfo > sourceDestPropMap2 = new KeyValuePair < PropertyInfo, PropertyInfo > (
- // Value prop of Selected Item
- typeof(SelectListItem).GetProperty("Value"),
- // Id prop from T class
- typeof(T).GetProperty("Id"));
- var name = "i";
- // i
- var paramExpr = Expression.Parameter(typeof(T), name);
- // i.Name
- var propertyA = Expression.Property(paramExpr, sourceDestPropMap1.Value);
- // i.Id
- var propertyB = Expression.Property(paramExpr, sourceDestPropMap2.Value);
- // i.Id.Tostring()
- var propertyBToString = Expression.Call(propertyB, typeof(object).GetMethod("ToString"));
- // new SelectListItem()
- var createObject = Expression.New(typeof(SelectListItem));
- // new SelectListItem() { Text = i.Name, Value = i.Id.ToString() }
- var InitializePropertiesOnObject = Expression.MemberInit(
- createObject,
- new []
- {
- Expression.Bind(sourceDestPropMap1.Key, propertyA),
- Expression.Bind(sourceDestPropMap2.Key, propertyBToString)
- });
- // i => new SelectListItem() { Text = i.Name, Value = i.Id.ToString() };
- var selectExpression = Expression.Lambda < Func < T,
- SelectListItem >> (InitializePropertiesOnObject, paramExpr);
- return source.Select(selectExpression).ToList();
- }
- }
- db.TestDemo1.GetList();
- db.TestDemo2.GetList();
- db.TestDemo3.GetList();
- db.TestDemo4.GetList();
Hope you enjoyed reading this post. Don’t forget to like/comment/share.

Delpin Susai RajPosted Aug 30, 2016, 8:34 AM
Nice one
Sonu ChaudharyPosted May 26, 2016, 10:32 AM
good one
Bhuvanesh MohankumarPosted May 6, 2016, 3:53 PM
Good one...
Asfend YarPosted Mar 3, 2016, 3:34 PM
very nice
Kumaresh RajalingamPosted Feb 14, 2016, 1:34 AM
Nice share
Mohammed IbrahimPosted Feb 4, 2016, 1:49 PM
nice
Humayun Kabir MamunPosted Feb 3, 2016, 11:04 PM
Nice...
Santhakumar MunuswamyPosted Feb 3, 2016, 3:10 PM
Thanks for nice article
Hemant SrivastavaPosted Feb 3, 2016, 11:08 AM
Good information and nicely written !
Amit ChoudharyPosted Feb 3, 2016, 10:05 AM
@Editorial team please update the note in header of article. It should be "Note – The article is applied for .Net version > 3.5 and C# > 3.0." and not "Note – The article is applied for .Net version 3.5 and C# 3.0." Kindly update. Thanks. cc Praveen Moosad
Amit ChoudharyPosted Feb 3, 2016, 10:01 AM
Thankyou everyone.
Manoj KallaPosted Feb 3, 2016, 5:15 AM
Good..
Nanddeep NachanPosted Feb 3, 2016, 1:17 AM
Nice share
Shubham KumarPosted Feb 3, 2016, 12:32 AM
thnx sir
Sibeesh VenuPosted Feb 3, 2016, 12:29 AM
Nice Share
Debasis SahaPosted Feb 2, 2016, 11:48 PM
Good One..
Mohammed IbrahimPosted Feb 2, 2016, 2:09 PM
nice
Pramod ThakurPosted Feb 2, 2016, 12:50 PM
thanks for sharing..
Upendra Pratap ShahiPosted Feb 2, 2016, 12:24 PM
nice share..