54 lines
1.7 KiB
C#
54 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Linq.Expressions;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace gehGassi.Common.Extensions
|
|
{
|
|
public static class OrderExtensions
|
|
{
|
|
|
|
public static IOrderedQueryable<T> SpecialOrderBy<T>(this IQueryable<T> source, string propertyName, SortDirection sortDirection = SortDirection.Ascending)
|
|
{
|
|
if (sortDirection == SortDirection.Ascending)
|
|
return source.OrderBy(ToLambda<T>(propertyName));
|
|
return source.OrderByDescending(ToLambda<T>(propertyName));
|
|
}
|
|
|
|
|
|
public static IOrderedQueryable<T> SpecialThenBy<T>(this IOrderedQueryable<T> source, string propertyName, SortDirection sortDirection = SortDirection.Ascending)
|
|
{
|
|
if (sortDirection == SortDirection.Ascending)
|
|
return source.ThenBy(ToLambda<T>(propertyName));
|
|
return source.ThenByDescending(ToLambda<T>(propertyName));
|
|
}
|
|
|
|
private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
|
|
{
|
|
var parameter = Expression.Parameter(typeof(T));
|
|
var property = Expression.Property(parameter, propertyName);
|
|
var convertedProperty = Expression.Convert(property, typeof(object));
|
|
|
|
return Expression.Lambda<Func<T, object>>(convertedProperty, parameter);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sortierrichtung
|
|
/// </summary>
|
|
public enum SortDirection
|
|
{
|
|
/// <summary>
|
|
/// Aufsteigend
|
|
/// </summary>
|
|
Ascending = 1,
|
|
/// <summary>
|
|
/// Absteigend
|
|
/// </summary>
|
|
Descending = 2
|
|
}
|
|
}
|