码迷,mamicode.com
首页 > 其他好文 > 详细

EF下lambda与linq查询&&扩展方法

时间:2018-09-12 12:31:39      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:.sh   arp   orderby   HERE   排序   类型   list   wms   要求   

1. linq查询数据

WebTestDBEntities db = new WebTestDBEntities();

  

1.1 linq查询所有列数据

     var userInfoList = from u in db.UserInfo
                               where u.ID == 10
                               select u;

1.2 linq查询部分列数据

   var userInfoList = from u in db.UserInfo
                               where u.ID >= 1
                               select new { Name = u.UserName, Pwd = u.UserPass };

            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.Name + ":" + userInfo.Pwd + "<br/>");
            }

 

2. lambda查询数据

2.1 lambda查询所有列数据

 var userInfoList = db.UserInfo.Where<UserInfo>(u => u.ID > 0);
            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.UserName + ":" + userInfo.UserPass + "<br/>");
            }

 

2.2 lambda查询部分列数据

    var userInfoList = db.UserInfo.Where<UserInfo>(u => u.ID > 0).Select(a => new { Name = a.UserName, Pwd = a.UserPass });
            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.Name + ":" + userInfo.Pwd + "<br/>");
            }

 

3. 排序

var userInfoList = db.UserInfo.Where<UserInfo>(c => true).OrderBy<UserInfo, int>(u => u.ID).Select(u => new { Name = u.UserName,Email=u.Email });//升序排序

            var userInfoList = db.UserInfo.Where<UserInfo>(c => true).OrderByDescending<UserInfo, int>(u => u.ID).Select(u => new { Name = u.UserName, Email = u.Email });//降序排序

            var userInfoList = (from u in db.UserInfo
                                select u).OrderByDescending<UserInfo, int>(c => c.ID).Select(u => new { Name = u.UserName, Email = u.Email });

 

4. 分页查询示例:

   int pageIndex = 2;
            int pageSize = 2;
            var userInfoList = db.UserInfo.Where<UserInfo>(c => true).OrderBy<UserInfo, int>(u => u.ID).Skip<UserInfo>((pageIndex - 1) * pageSize).Take<UserInfo>(pageSize);
            foreach (var userInfo in userInfoList)
            {
                Response.Write(userInfo.UserName + "<br/>");
            }

5、扩展方法

语法要求:

  • 扩展方法所在的类必须是static
  • 扩展方法必须是一个静态方法
  • 扩展方法的第一个参数,必须用this关键字修饰,而且类型是所扩展的类型
  •   public static string ShowMsg(this string ext, string msg)
            {
                return string.Format("<span style=‘color:red‘>{0}</span>", msg);
            }
 string tempStr = string.Empty;
            string resultStr = tempStr.ShowMsg("扩展方法示例");
            Response.Write(resultStr);

 

EF下lambda与linq查询&&扩展方法

标签:.sh   arp   orderby   HERE   排序   类型   list   wms   要求   

原文地址:https://www.cnblogs.com/ZaraNet/p/9634093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!