Create Dynamic LINQ Using Expressions

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:

  1. Parameters = {a, b}  
  2. Body = a + b  
  3. NodeType = Lambda  
So we would need to declare two parameters first. Which we can do like below:
  1. var paramExprA = Expression.Parameter(typeof(int), "a");  
  2. var paramExprB = Expression.Parameter(typeof(int), "b");  
Now let’s build the body, as we can see the body is a binary operation being performed with add operator. So it will be a binary expression, with Add method and pass those parameters expression to it.
  1. var body = BinaryExpression.Add(paramExprA, paramExprB);  
So now we have our parameters and body. Node type will stick them together:
  1. var lambda = Expression.Lambda<Func<intintint>>(body, paramExprA, paramExprB);  
We have defined the Lambda type as Func with two argument of int and return type int. Then supply the body and parameters expression. And the expression is complete. Now if you look at the lambda in debug mode it will look like exactly that it supposed to be.

Now to execute it, we have to do the same as declared Expressions.

expression

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

expression

The method can be generalized with generics and then it can be called with any types:
  1. private static Expression < Func < T, T, T >> BuildIt < T > ()   
  2. {  
  3.     var paramExprA = Expression.Parameter(typeof(T), "a");  
  4.     var paramExprB = Expression.Parameter(typeof(T), "b");  
  5.   
  6.     var body = BinaryExpression.Add(paramExprA, paramExprB);  
  7.   
  8.     var lambda = Expression.Lambda < Func < T,  
  9.         T, T >> (body, paramExprA, paramExprB);  
  10.   
  11.     return lambda;  
  12. }  
You can call it like:

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:
  1. MyDbContext db = new MyDbContext();  
  2.   
  3. List < SelectListItem > selectedItems = new List < SelectListItem > ();  
  4. if (type == nullreturn selectedItems;  
  5.   
  6. if (type == typeof(TestDemo))  
  7.     selectedItems = db.TestDemo.Select(i => new SelectListItem  
  8.     {  
  9.         Text = i.Name, Value = i.Id.ToString()  
  10.     }).ToList();  
  11. if (type == typeof(TestDemo1))  
  12.     selectedItems = db.TestDemo1.Select(i => new SelectListItem  
  13.     {  
  14.         Text = i.Name, Value = i.Id.ToString()  
  15.     }).ToList();  
  16.   
  17. if (type == typeof(TestDemo2))  
  18.     selectedItems = db.TestDemo2.Select(i => new SelectListItem  
  19.     {  
  20.         Text = i.Name, Value = i.Id.ToString()  
  21.     }).ToList();  
  22.   
  23. if (type == typeof(TestDemo3))  
  24.     selectedItems = db.TestDemo3.Select(i => new SelectListItem  
  25.     {  
  26.         Text = i.Name, Value = i.Id.ToString()  
  27.     }).ToList();  
This code is one of the question from SO. Where the person asked to refactor this code. And ofcourse this looks bit awkward to have same LINQ select criteria repeated to all classes. Now assume if you have such 10-12 classes how the method would look.

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.
  1. i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() };  
So we have the following items so far:
  1. Parameters = i  
  2. Body = new SelectListItem { Text = i.Name, Value = i.Id.ToString() }  
  3. NodeType = Lambda  
So let’ start with creating the parameters first:
  1. var paramExpr = Expression.Parameter(typeof(T), "i");  
Now we’ll create the body as second step. But I’ll discuss the body part in details because it has a couple of things to perform.

 

  • 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.

  1. KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap1  
  2. new KeyValuePair<PropertyInfo, PropertyInfo>(  
  3. // Text prop of selected item  
  4. typeof(SelectListItem).GetProperty("Text"),  
  5. // Name prop of T class  
  6. typeof(T).GetProperty("Name"));   
  7.   
  8. KeyValuePair<PropertyInfo, PropertyInfo> sourceDestPropMap2  
  9. new KeyValuePair<PropertyInfo, PropertyInfo>(  
  10. // Value prop of Selected Item  
  11. typeof(SelectListItem).GetProperty("Value"),  
  12. // Id prop from T class  
  13. typeof(T).GetProperty("Id"));   
Now let us define the property Map first.
  1. var propertyA = Expression.Property(paramExpr, sourceDestPropMap1.Value);  
  2.   
  3. var propertyB = Expression.Property(paramExpr, sourceDestPropMap2.Value);  
Since we need to invoke the ‘ToString’ method on second property.
  1. var propertyBToString = Expression.Call(propertyB, typeof(object).GetMethod("ToString"));  
Now let’s define the object creation of `SelecListItem` class and property initialization.
  1. var createObject = Expression.New(typeof(SelectListItem));  
  2.   
  3. var InitializePropertiesOnObject = Expression.MemberInit(  
  4.     createObject,  
  5.     new []   
  6.     {  
  7.         Expression.Bind(sourceDestPropMap1.Key, propertyA),  
  8.             Expression.Bind(sourceDestPropMap2.Key, propertyBToString)  
  9.     });  
Now we have almost defined the object creation, property initialization and property mapping from parameter Expression of Type T to SelectListItem. The final step is to build the expression.
  1. var selectExpression = Expression.Lambda<Func<T, SelectListItem>>(InitializePropertiesOnObject, paramExpr);  
Let’s see how our expression look like with Debugger visualizer.

visualizer

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.
  1. return source.Select(selectExpression).ToList();  
Here’s a complete method source,
  1. public static class QueryableExtension  
  2. {  
  3.     public static IEnumerable < SelectListItem > GetTable < T > (this IQueryable < T > source)  
  4.     {  
  5.   
  6.   
  7.         KeyValuePair < PropertyInfo, PropertyInfo > sourceDestPropMap1 = new KeyValuePair < PropertyInfo, PropertyInfo > (  
  8.             // Text prop of selected item  
  9.             typeof(SelectListItem).GetProperty("Text"),  
  10.             // Name prop of T class  
  11.             typeof(T).GetProperty("Name"));  
  12.   
  13.         KeyValuePair < PropertyInfo, PropertyInfo > sourceDestPropMap2 = new KeyValuePair < PropertyInfo, PropertyInfo > (  
  14.             // Value prop of Selected Item  
  15.             typeof(SelectListItem).GetProperty("Value"),  
  16.             // Id prop from T class  
  17.             typeof(T).GetProperty("Id"));  
  18.   
  19.         var name = "i";  
  20.   
  21.         // i  
  22.         var paramExpr = Expression.Parameter(typeof(T), name);  
  23.   
  24.         // i.Name  
  25.         var propertyA = Expression.Property(paramExpr, sourceDestPropMap1.Value);  
  26.         // i.Id  
  27.         var propertyB = Expression.Property(paramExpr, sourceDestPropMap2.Value);  
  28.   
  29.         // i.Id.Tostring()  
  30.         var propertyBToString = Expression.Call(propertyB, typeof(object).GetMethod("ToString"));  
  31.   
  32.         // new SelectListItem()  
  33.         var createObject = Expression.New(typeof(SelectListItem));  
  34.   
  35.         // new SelectListItem() { Text = i.Name, Value = i.Id.ToString() }  
  36.         var InitializePropertiesOnObject = Expression.MemberInit(  
  37.             createObject,  
  38.             new []  
  39.             {  
  40.                 Expression.Bind(sourceDestPropMap1.Key, propertyA),  
  41.                     Expression.Bind(sourceDestPropMap2.Key, propertyBToString)  
  42.             });  
  43.   
  44.         // i => new SelectListItem() { Text = i.Name, Value = i.Id.ToString() };  
  45.         var selectExpression = Expression.Lambda < Func < T,  
  46.             SelectListItem >> (InitializePropertiesOnObject, paramExpr);  
  47.   
  48.   
  49.         return source.Select(selectExpression).ToList();  
  50.     }  
  51. }  
Now instead of all the if..else from our sample snippet we can simply call this method like:
  1. db.TestDemo1.GetList();  
  2. db.TestDemo2.GetList();  
  3. db.TestDemo3.GetList();  
  4. db.TestDemo4.GetList();  
Similarly you can build any type of Expression and use it for Dynamic Linq. The objects mapping tool Automapper is using Expressions to build dynamic projection to map objects.

Hope you enjoyed reading this post. Don’t forget to like/comment/share.

 

Up Next
    Ebook Download
    View all
    Learn
    View all