This project allows you to create a list of expressions, and compile the to a single AND / OR linq query. very usefall when working whit dynamic queries.
First create a list of expressions, each expressions is comprised of a Func of an object, UserModel in the exmpales below, and bool.
var andList = new List<Expression<Func<UserModel,bool>>>(); andList.Add((o) => o.Last != "smith" && o.Age > 5); andList.Add((o) => o.Age > 5); andList.Add((o) => o.isTemp); andList.Add((o) => o.Rank == 1); var orList = new List<Expression<Func<UserModel,bool>>>(); andList.Add((o) => o.Age !=12); andList.Add((o) => o.Rank >2 1);
var query=ExpresionTreeBuilder.CreateANDQuery<UserModel>(andList).Compile(); var test = allUsers.Where(query);
Or create a compiled query.
var query=ExpresionTreeBuilder.CreateCompiledANDQuery<UserModel>(andList); var test = allUsers.Where(query);
var query=ExpresionTreeBuilder.CreateORQuery<UserModel>(OrList).Compile(); var test = allUsers.Where(query);
Or create a compiled query.
var query=ExpresionTreeBuilder.CreateCompiledOrQuery<UserModel>(OrList); var test = allUsers.Where(query);
var query=ExpresionTreeBuilder.CreateQuery<UserModel>(andList,OrList).Compile(); var test = allUsers.Where(query);
var query=ExpresionTreeBuilder.CreateCompiledQuery<UserModel>(andList,OrList); var test = allUsers.Where(query);
Each of the above methods can recive an optional bool param named sortProperties, deafult value is True. When this param is set to True it will sort the order of the queries in the list to make sure the 'easiest' come first.
the order is:
- bool
- Integers (Int and long)
- Floating point (Float, Double, Decimal)
- string and Guid
- datetime
- other
You can also create order by queries.
var orderAscList = new List<Expression<Func<UserModel,dynamic>>>(); var orderDescList2 = new List<Expression<Func<UserModel,dynamic>>>(); orderAscList.Add((o) => o.Age); orderDescList2.Add((o) => o.Rank);
allUsers = ExpresionTreeBuilder.CreateOrderASCQuery<UserModel>(allUsers, orderAscList);
allUsers = ExpresionTreeBuilder.CreateOrderDescQuery<UserModel>(allUsers, orderDescList2);
allUsers = ExpresionTreeBuilder.CreateOrderQuery<UserModel>(allUsers,orderAscList,orderDescList2,false);