Dynamic Linq

There are cases where you might need to use dynmaic linq in your Linq Queries, for instance filtering of items based on multiple where clause.

Assume you have list of following Items :


var listofmobiles = new List<Mobile>()

{ 

new Mobile(){ModelNo=1,MobileType= "Android"}

new Mobile(){ModelNo=2,MobileType= "Android"}

new Mobile(){ModelNo=3,MobileType= "BlackBerry"}

new Mobile(){ModelNo=4,MobileType= "Symbian"}

new Mobile(){ModelNo=5,MobileType= "IOS"

}

 }

public class Mobile

{

public long ModelNo {get;set;}

public string MobileType {get;set;}

}

We would write a simple linq query if we where suppose to query only one of mobiletype,assume a case where there can be more than one mobiletype(Android,Ios) the list should still return the items under Android and Ios.

Expression Trees :

To write Dynamic Linq queries,we must construct expression tress that matches the where clause.I am not going to explain more about expression tree but instead usage of System.Dynamic.Linq feature provided by framework which uses expression trees.

Using Dynamic Linq in where clause :

Given different mobiletype (Ios,Android,Symbain ) filter out the above list that matches the mobiletype.


var filterresult =listofmobiles.where("mobiletye @0 or mobiletye @1 or mobiletye @2","Android","IOS","Symbain").Tolist();