From 7570c39e65f24c98b07e36dbfc67fc169ab25c48 Mon Sep 17 00:00:00 2001 From: masoodafar-web Date: Tue, 23 Jun 2026 00:11:37 +0330 Subject: [PATCH] refactor(extensions): improve sorting logic in ApplyOrder method - 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. --- .../Common/Extensions/SortByExtensions.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/CMSMicroservice.Application/Common/Extensions/SortByExtensions.cs b/src/CMSMicroservice.Application/Common/Extensions/SortByExtensions.cs index 3f0d9c8..439e9a5 100644 --- a/src/CMSMicroservice.Application/Common/Extensions/SortByExtensions.cs +++ b/src/CMSMicroservice.Application/Common/Extensions/SortByExtensions.cs @@ -8,16 +8,31 @@ public static class SortByExtensions public static IQueryable ApplyOrder(this IQueryable source, string? sortBy) where TSource : BaseAuditableEntity { - // default sort approach if (sortBy is null or "") { - source = source.OrderByDescending(p => p.Created); - return source; + return source.OrderByDescending(p => p.Created); } - // sort using dynamic linq - source = source.OrderBy(sortBy); + return source.OrderBy(NormalizeSortBy(sortBy)); + } - return source; + /// + /// Dynamic LINQ treats "-Created" as unary minus on DateTime (invalid). + /// Project convention: leading '-' means descending sort. + /// + 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; } }