0

I have a method like below ->

public static IOrderedQueryable<PurchaseOrder> GetOrders(bool ascending,string orderByField, IQueryable<PurchaseOrder> purchaseOrders)
{
        
        switch (orderByField)
        {
                case "OrderNumber":
                    return ascending ? purchaseOrders.OrderBy(x => x.OrderNumber) :
                                            purchaseOrders.OrderByDescending(x => x.OrderNumber);


                case "DeliveryDate":
                    return ascending ?
                                         purchaseOrders.OrderBy(x => x.DeliveryDate) :
                                         purchaseOrders.OrderByDescending(x => x.DeliveryDate);
                default:
                    return ascending ?
                                         purchaseOrders.OrderBy(x => x.OrderDate) :
                                         purchaseOrders.OrderByDescending(x => x.OrderDate);
        }
}

I want to dynamically order "purchaseOrders". Somthing like

purchaseOrders.OrderBy(orderByField) OR OrderByDescending(orderByField) //this is just an idea what is want to do.

After that I want to move the code part

ascending ? purchaseOrders.OrderBy(x => x.OrderNumber) :
                                            purchaseOrders.OrderByDescending(x => x.OrderNumber);

Inside a method and I can reuse it. Is there any way to do that? If any then please let me know.

Note: If any code create any confusion please let me know.

Srijon Chakraborty
  • 2,007
  • 2
  • 7
  • 20

0 Answers0