.NET[C#]LINQ中如何按多个属性排序?
问题描述
比如有如下实体:
public class Movies {
public int Id{get;set;}
public int CategoryID {get;set;}
public string Name {get;set;}
}
需要按分类ID CategoryID 和名称 Name 排序,类似:
var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })
如何实现呢?
方案一
使用lambda:
var movies = _db.Movies.OrderBy(c => c.CategoryID).ThenBy(n => n.Name)
方案二
使用非lambda:
var movies = from row in _db.Movies
orderby row.CategoryID, row.Name
select row;
如果需要指定排序方向,则:
var movies = from row in _db.Movies
orderby row.CategoryID descending, row.Name
select row;
方案三
var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })
方案四
编写一个静态扩展方法,如下:
public static class IQueryableExtension
{
public static bool IsOrdered<T>(this IQueryable<T> queryable) {
if(queryable == null) {
throw new ArgumentNullException("queryable");
}
return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
}
public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
if(queryable.IsOrdered()) {
var orderedQuery = queryable as IOrderedQueryable<T>;
return orderedQuery.ThenBy(keySelector);
} else {
return queryable.OrderBy(keySelector);
}
}
public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
if(queryable.IsOrdered()) {
var orderedQuery = queryable as IOrderedQueryable<T>;
return orderedQuery.ThenByDescending(keySelector);
} else {
return queryable.OrderByDescending(keySelector);
}
}
}
调用方法:
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册