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/>"); }
语法要求:
- 扩展方法所在的类必须是
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);