Lambda Expressions expression, lambdaexpressions
Most of the time we use Lambda expressions to query user data, such as using Lambda expressions to query user data, sometimes querying user information by phone or email, and sometimes querying user information by user name
var user = db.Set<U_User>().Where(c => c.UserName = "nee32"); var user = db.Set<U_User>().Where(c => c.TelePhone = "13888888888");
In fact, the query results are the same, but the only difference is that the conditions in Lambda expressions are different. Can I write only one query method and implement Where statements with query conditions? The answer is yes, of course! For example, if you use one method in a three-tier architecture to meet multiple condition queries, the Code is as follows:
Public class UserDAL {// <summary> /// search for the user list based on the conditions /// </summary> /// <param name = "where"> </param> /// <returns> </returns> public List <U_User> FindAll (System. linq. expressions. func <U_User, bool> where = null) {using (EFContext db = new EFContext () {if (where = null) return db. u_User.ToList (); else return db. u_User.Where (where ). toList ();}}}
A FindAll method is declared. The parameter is an empty Lambda expression (Expression <Func <U_User, bool> indicates a Lambda Expression.)
Func <U_User, bool> uses a generic delegate to pass in U_User, and returns a bool value.
Method call
public ActionResult Index() { //List<U_User> userList = userBLL.FindAll(c => c.UserName == "nee32"); //List<U_User> userList = userBLL.FindAll(c => c.UserName == "nee32" && c.Status == 1); List<U_User> userList = userBLL.FindAll(); return View(); }
Use Expression to pagination. Note thatYou must sort the data by page.The paging code is as follows:
/// <Typeparam name = "TKey"> sort field type </typeparam> /// <param name = "pageIndex"> current page </param> /// <param name = "pageSize"> Number of entries per page </param> /// <param name = "orderby"> sort field Lambda expression </param> /// <param name = "where"> query condition Lambda expression </param> // <returns> </returns> public List <U_User> GetPageList <TKey> (int pageIndex, int pageSize, Expression <Func <U_User, TKey> orderby, Expression <Func <U_User, bool> where = null) {u Sing (EFContext db = new EFContext () {var query = from d in db. U_User select d; if (where! = Null) {query = query. where (where);} var data = query. orderBy (orderby ). skip (pageIndex-1) * pageSize ). take (pageSize ). toList (); return data ;}}
Paging method call
public ActionResult Index() { List<U_User> userList = userBLL.GetPageList(1, 20, c => c.CreateTime, c => c.UserName == "nee32"); return View(userList); }