封装一个ISortable接口

时间:2021-12-17 19:24:35

using System;
/// <summary>
/// 排序规范
/// </summary>
/// <typeparam name="T"></typeparam>
using System.Linq.Expressions;
public interface ISortable<T>
{
/// <summary>
/// 递增
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
ISortable<T> Asc<TKey>(global::System.Linq.Expressions.Expression<Func<T, TKey>> keySelector);
/// <summary>
/// 然后递增
/// </summary>
/// <typeparam name="TKey1"></typeparam>
/// <typeparam name="TKey2"></typeparam>
/// <param name="keySelector1"></param>
/// <returns></returns>
ISortable<T> ThenAsc<TKey>(Expression<Func<T, TKey>> keySelector);
/// <summary>
/// 递减
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
ISortable<T> Desc<TKey>(global::System.Linq.Expressions.Expression<Func<T, TKey>> keySelector);
/// <summary>
/// 然后递减
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
ISortable<T> ThenDesc<TKey>(Expression<Func<T, TKey>> keySelector);
/// <summary>
/// 排序后的结果集
/// </summary>
global::System.Linq.IQueryable<T> Queryable { get; }
}

实现接口:

using System;
using System.Linq;
using System.Linq.Expressions;
namespace EntityFrameworks.Data.Core
{
/// <summary>
/// Linq架构里对集合排序实现
/// </summary>
/// <typeparam name="T"></typeparam>
public class Orderable<T> : ISortable<T>
{
private IQueryable<T> _queryable;

/// <summary>
/// 排序后的结果集
/// </summary>
/// <param name="enumerable"></param>
public Orderable(IQueryable<T> enumerable)
{
_queryable = enumerable;
}

/// <summary>
/// 排序之后的结果集
/// </summary>
public IQueryable<T> Queryable
{
get { return _queryable; }
}
/// <summary>
/// 递增
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
public ISortable<T> Asc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = (_queryable as IOrderedQueryable<T>)
.OrderBy(keySelector);
return this;
}
/// <summary>
/// 然后递增
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
public ISortable<T> ThenAsc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = (_queryable as IOrderedQueryable<T>)
.ThenBy(keySelector);
return this;
}
/// <summary>
/// 递减
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
public ISortable<T> Desc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = _queryable
.OrderByDescending(keySelector);
return this;
}
/// <summary>
/// 然后递减
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <param name="keySelector"></param>
/// <returns></returns>
public ISortable<T> ThenDesc<TKey>(Expression<Func<T, TKey>> keySelector)
{
_queryable = (_queryable as IOrderedQueryable<T>)
.ThenByDescending(keySelector);
return this;
}
}
}