Skip to content

Commit e03dfb5

Browse files
committed
Adding order by functionality
1 parent bff7022 commit e03dfb5

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

NorthwindCRUD/Controllers/ProductsController.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace NorthwindCRUD.Controllers
22
{
3+
using System.Reflection;
34
using AutoMapper;
45
using Microsoft.AspNetCore.Authorization;
56
using Microsoft.AspNetCore.Mvc;
@@ -48,9 +49,10 @@ public ActionResult<ProductDto[]> GetAll()
4849
/// </summary>
4950
/// <param name="skip">Previously called pageNumber. The number of the page to fetch. If this parameter is not provided, all products are fetched.</param>
5051
/// <param name="top">Previously called pageSize. The size of the page to fetch. If this parameter is not provided, all products are fetched.</param>
52+
/// <param name="orderBy">The fields to order by, in the format "field1 asc, field2 desc". If not provided, defaults to no specific order.</param>
5153
/// <returns>A ProductDtoCollection object containing the fetched products and the total record count.</returns>
5254
[HttpGet("GetAllPagedProducts")]
53-
public ActionResult<ProductDtoCollection> GetAllProducts(int? skip, int? top)
55+
public ActionResult<ProductDtoCollection> GetAllProducts(int? skip, int? top, string? orderBy)
5456
{
5557
try
5658
{
@@ -62,6 +64,22 @@ public ActionResult<ProductDtoCollection> GetAllProducts(int? skip, int? top)
6264
int skipRecordsAmount = skip ?? 0;
6365
int currentSize = top ?? totalRecords;
6466

67+
// Apply ordering if specified
68+
if (!string.IsNullOrEmpty(orderBy))
69+
{
70+
var orderByParts = orderBy.Split(' ');
71+
var field = orderByParts[0];
72+
var order = orderByParts.Length > 1 ? orderByParts[1] : "ASC";
73+
74+
// Get the property info of the field to order by
75+
var propertyInfo = products.First().GetType().GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
76+
77+
// Use dynamic LINQ to sort based on field and order
78+
products = order.ToUpper() == "DESC"
79+
? products.OrderByDescending(e => propertyInfo?.GetValue(e, null)).ToArray()
80+
: products.OrderBy(e => propertyInfo?.GetValue(e, null)).ToArray();
81+
}
82+
6583
// Apply pagination
6684
var pagedProducts = products
6785
.Skip(skipRecordsAmount)

0 commit comments

Comments
 (0)