Files
CMS/src/CMSMicroservice.Application/Common/Extensions/SortByExtensions.cs
T
masoodafar-web 7570c39e65
Build and Deploy to Kubernetes / build-and-deploy (push) Failing after 21m1s
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.
2026-06-23 00:11:37 +03:30

39 lines
1.0 KiB
C#

using System.Linq.Dynamic.Core;
using CMSMicroservice.Domain.Common;
namespace CMSMicroservice.Application.Common.Extensions;
public static class SortByExtensions
{
public static IQueryable<TSource> ApplyOrder<TSource>(this IQueryable<TSource> source,
string? sortBy) where TSource : BaseAuditableEntity
{
if (sortBy is null or "")
{
return source.OrderByDescending(p => p.Created);
}
return source.OrderBy(NormalizeSortBy(sortBy));
}
/// <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;
}
}