ZEXSM / OData.QueryBuilder

OData.QueryBuilder - library for creating complex OData queries (OData version 4.01) based on data models with linq syntax.
MIT License
72 stars 31 forks source link

Sorting multiple fields #39

Closed ricardo-valero closed 3 years ago

ricardo-valero commented 3 years ago

Hi! I'm trying to use this library with Blazor Wasm, so far so good, but...

I was trying to combine sorting of columns, but I just couldn't. For example:

$orderBy=Number desc, Description asc

I know the methods look like this right now:

public IODataOptionList<TEntity> OrderBy(Expression<Func<TEntity, object>> entityOrderBy)
{
    var query = _visitorExpression.ToString(entityOrderBy.Body);

    _stringBuilder.Append($"{ODataOptionNames.OrderBy}{QuerySeparators.EqualSignString}{query} {QuerySorts.Asc}{QuerySeparators.MainString}");

    return this;
}

public IODataOptionList<TEntity> OrderByDescending(Expression<Func<TEntity, object>> entityOrderByDescending)
{
    var query = _visitorExpression.ToString(entityOrderByDescending.Body);

    _stringBuilder.Append($"{ODataOptionNames.OrderBy}{QuerySeparators.EqualSignString}{query} {QuerySorts.Desc}{QuerySeparators.MainString}");

    return this;
}

Couldn't we have another overloaded method for OrderBy where we pass as an argument whether each expression is ascending or descending? Maybe reusing QuerySorts? I don't know much about this (that's why I haven't forked it and made it myself, but I also wish to learn and contribute) Maybe something similar to IODataFunction and IODataOperator with Filter?

public IODataOptionList<TEntity> OrderBy(Expression<Func<TEntity, IODataSort, object>> entityOrderBy)
{
    var query = _visitorExpression.ToString(entityOrderBy.Body);

    _stringBuilder.Append($"{ODataOptionNames.OrderBy}{QuerySeparators.EqualSignString}{query} {QuerySeparators.MainString}");

    return this;
}

Desired usage:

.OrderBy((s, x) => x.Ascending(s.Sum))

And for multiple:

.OrderBy((s, x) => new { x.Ascending(s.Sum), x.Descending(s.Type) }))

I really don't know, but I'd be glad if this feature could be added.

ZEXSM commented 3 years ago

Hi! I'll take a close look at the proposal and check some things. Later I will come back with an answer or counter proposal.

ZEXSM commented 3 years ago

Hi, I checked and re-looked the proposed option and I think it can be implemented. I'm waiting for PR or when I have time to implement it myself.

ZEXSM commented 3 years ago

Hi added sorting by several fields with indication of direction https://github.com/ZEXSM/OData.QueryBuilder/tree/feature/sorting-multiple-fields#orderby

Option with .OrderBy ((s, x) => new {x.Ascending (s.Sum), x.Descending (s.Type)})) in my opinion it is not suitable because you have to specify the name of the property. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types