DynamicWhere.ex
DynamicWhere.exv2.1.5·docs

.Order<T>(...)

Sorts the query by one or multiple OrderBy criteria. Two overloads are available — one for a single criterion, one for a list.

Single overload

public static IQueryable<T> Order<T>(this IQueryable<T> query, OrderBy order)
    where T : class

List overload

public static IQueryable<T> Order<T>(this IQueryable<T> query, List<OrderBy> orders)
    where T : class
ParameterTypeDescription
order / ordersOrderBy / List<OrderBy>Sort criteria. Each entry's Sort determines priority (lower = first).

Validations

  • Field must be non-empty and valid on T (case-insensitive, auto-normalized).
  • Field may not end on a collection of entities or other complex types — there is no single value to compare.

Returns

IQueryable<T> — ordered query.

Collection paths

A sort needs one comparable value per row, so a path that crosses a collection navigation cannot be emitted verbatim — List<Tag> has no Value member. Each collection segment is reduced with an aggregate instead: Min when sorting ascending, Max when sorting descending — rows are ordered by their best matching element in the requested direction.

FieldDirectionGenerated expression
Category.NameAscendingCategory.Name asc
Tags.ValueAscendingTags.Min(Value) asc
Tags.ValueDescendingTags.Max(Value) desc
OrderItems.Product.NameAscendingOrderItems.Min(Product.Name) asc
OrderItems.UnitPriceAscendingOrderItems.Select(UnitPrice).DefaultIfEmpty().Min() asc

Rows whose collection is empty have nothing to sort by. Reference and nullable types yield null; non-nullable value types (int, decimal, DateTime, …) use DefaultIfEmpty() and yield the type default, which keeps in-memory sorting from throwing Sequence contains no elements.

// Products sorted by their cheapest line item, cheapest product first
var ordered = dbContext.Orders.Order(new OrderBy
{
    Sort = 1,
    Field = "OrderItems.UnitPrice",
    Direction = Direction.Ascending
});

Example — single order

var ordered = dbContext.Products.Order(new OrderBy
{
    Sort = 1,
    Field = "CreatedAt",
    Direction = Direction.Descending
});
{
  "sort": 1,
  "field": "CreatedAt",
  "direction": "Descending"
}

Example — multiple orders

var ordered = dbContext.Customers.Order(new List<OrderBy>
{
    new OrderBy { Sort = 1, Field = "LastName",  Direction = Direction.Ascending },
    new OrderBy { Sort = 2, Field = "FirstName", Direction = Direction.Ascending }
});
[
  { "sort": 1, "field": "LastName",  "direction": "Ascending" },
  { "sort": 2, "field": "FirstName", "direction": "Ascending" }
]

See also