为项目中使用所写,扩展实现根据实体自动生成排序,支持多字段排序。但必须与查询实体大小写匹配。
一,建立排序实体。
/// <summary>
/// 排序条件模型
/// </summary>
public class OrderItemModel
{
public string FieldName { get; set; }
public string SortType { get; set; }
}
二,扩展orderby。
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, List<OrderItemModel> oims)
{
if (source == null) throw new ArgumentNullException("source");
var bNull = oims.TrueForAll(s =>
{
if (s.FieldName.IsEmpty() && s.SortType.IsEmpty())
return false;
else
return true;
});
if (!bNull) return source;
string propertyName = string.Empty, sortDirection =