orderby:C#3.0入门系列( 6)-的OrderBy操作来源: 发布时间:星期二, 2009年2月17日 浏览:10次 评论:0
本节讲orderby操作.我突然在想这么个问题读者会T-SQL吗?要是不知道那我写是不是太简单了呢?做个调查哦不知道举手.
OrderBy操作 简单按雇用日期排序默认为升序 varq= 带where条件shipcity为london varq= 或 varq= 在这里where和orderby顺序并不重要而在T-SQL中where和orderby有严格位置限制 OrderByDescending按价格降序 varq= ThenBy和ThenByDescending也就是按多个列进行排序第个列子是先按citycity相同再按contactname排序第 2个例子中第 2序列为降序 ThenBy: 对这两个句子解释下 对于ThenBy操作其级连形式为: varq=db.Customers.OrderBy(c=>c.City).ThenBy(c=>c.ContactName).ToList; T-SQL中并没有ThenBy语句其依然翻译为OrderBy 所以也可以用下面语句来表达 varq=db.Customers.OrderBy(c=>c.ContactName).OrderBy(c=>c.City).ToList; 所要注意是是两个orderby顺序多个orderby操作时级连方式是按逆序.即先按city排时city要放在最后 对于降序用相应降序操作符替换即刻 varq=db.Customers.OrderByDescending(c=>c.City).ThenByDescending(c=>c.ContactName).ToList; 需要介绍说明是orderby操作不支持按type排序也不支持匿名类 比如 var q = db.Customers.OrderBy(c => c).ToList;和 var q = db.Customers.OrderBy(c => {c.City,c.ContactName}).ToList; 会被抛出异常但是既然提了大家在这个问题就不会犯常见是前面操作有匿名类再跟orderby时比较是类别比如 var q = db.Customers.Select(c => { c.City, c.Address }).OrderBy(c => c).ToList; 如果你想使用OrderBy(c => c)其前提条件是前面步骤中所产生对象类别必须为C#语言基本类型比如 var q = db.Customers.Select(c=>c.City).OrderBy(c => c).ToList; city为类型 还有点需要介绍说明时linq和dlinq在orderby操作中稍微有点区别linq支持按type排序但是需要你自己去实现IComparable接口 比如语句:var q = db.Customers.ToList.OrderBy(c => c).ToList; 第个ToList会把数据库中所有数据取出放到内存中以后所有操作全部是对内存操作后面所有操作均为linq操作不是dlinq(这点我前面文章中讲过)如果你想用按客户进行排序你必须在Customer类中实现IComparable接口 其Customer类必须从IComparable继承代码如下 public partial Customers : .Data.Linq.INotyPropertyChanging, .ComponentModel.INotyPropertyChanged,IComparable Icomparable接口具体实现如下: #regionIComparableMembers Orderby操作会自动该接口思路方法实现按类别排序如果你映射文件中没有实现该接口系统会抛出异常 你也可以使用generic如下 public partial Customers : .Data.Linq.INotyPropertyChanging, .ComponentModel.INotyPropertyChanged,IComparable<Customers> #regionIComparable<Customers>Members 好处就是你无须把object强制转化为customer类 我们再来定义个先按订单号排序相同订单按产品号排序 public partial OrderDetails : .Data.Linq.INotyPropertyChanging, .ComponentModel.INotyPropertyChanged,IComparable<OrderDetails> #regionIComparable<OrderDetails>Members 好了更多功能等待大家自己去实现下次讲Groupby操作 0
相关文章读者评论发表评论 |
|