refactor(extensions): improve sorting logic in ApplyOrder method
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 21m1s
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 21m1s
- Simplified the default sorting approach by directly returning the ordered source. - Introduced NormalizeSortBy method to handle dynamic LINQ sorting, accommodating leading '+' and '-' for ascending and descending order respectively. - Enhanced code clarity and maintainability by reducing unnecessary variable assignments.
This commit is contained in:
@@ -8,16 +8,31 @@ public static class SortByExtensions
|
|||||||
public static IQueryable<TSource> ApplyOrder<TSource>(this IQueryable<TSource> source,
|
public static IQueryable<TSource> ApplyOrder<TSource>(this IQueryable<TSource> source,
|
||||||
string? sortBy) where TSource : BaseAuditableEntity
|
string? sortBy) where TSource : BaseAuditableEntity
|
||||||
{
|
{
|
||||||
// default sort approach
|
|
||||||
if (sortBy is null or "")
|
if (sortBy is null or "")
|
||||||
{
|
{
|
||||||
source = source.OrderByDescending(p => p.Created);
|
return source.OrderByDescending(p => p.Created);
|
||||||
return source;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// sort using dynamic linq
|
return source.OrderBy(NormalizeSortBy(sortBy));
|
||||||
source = source.OrderBy(sortBy);
|
}
|
||||||
|
|
||||||
return source;
|
/// <summary>
|
||||||
|
/// Dynamic LINQ treats "-Created" as unary minus on DateTime (invalid).
|
||||||
|
/// Project convention: leading '-' means descending sort.
|
||||||
|
/// </summary>
|
||||||
|
private static string NormalizeSortBy(string sortBy)
|
||||||
|
{
|
||||||
|
sortBy = sortBy.Trim();
|
||||||
|
if (sortBy.StartsWith('-') && sortBy.Length > 1)
|
||||||
|
{
|
||||||
|
return $"{sortBy[1..]} descending";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sortBy.StartsWith('+') && sortBy.Length > 1)
|
||||||
|
{
|
||||||
|
return $"{sortBy[1..]} ascending";
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortBy;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user