0

There are methods in MongoDB C# driver (or any other libraries) that expect an expression only as a parameter like:

query.SortByDescending(x => x.Name) // sort by name for example

What I would like to do is to receive the field "Name" as a string and be able to sort by it at runtime:

var sortBy = "Name";
query.SortByDescending(x => x."SortyBy") // something like this

i.e how to create an expression to be x => x.(value of sortBy)?

1
  • Why are you wanting to do this? There may be a much easier way to get what you need. Commented Jun 30, 2022 at 4:07

1 Answer 1

4

This question basically has the same answer as your question yesterday.

The reason the answer is essentially the same is simply that FieldDefinition<T> is implicitly castable from string, so you can pass a string anywhere you see a FieldDefinition<T> argument.

Therefore, we can use the .Sort method (since that takes a SortDefinition<T>) and use Builders<T>.Sort.Descending which takes a FieldDefinition<TElement> and returns the SortDefinition<T> that we need:

query = query.Sort(Builders<Items>.Sort.Descending(sortBy));

I'm assuming your document type is Items here as it was in your question yesterday.

Note that the textual name you use here has to match the name in the database, which isn't necessarily the same as your document's property name. If you want to make it more robust, then you'll want to use expression trees to produce an expression for the property in question.


An alternative solution would be to build the Expression<Func<T, TElement>> that SortByDescending requires:

private static Expression<Func<TDocument, object>> GetPropertyExpression<TDocument>(string propertyName)
{
    var parameter = Expression.Parameter(typeof(TDocument));
    var property = Expression.Property(parameter, propertyName);
    var castResult = Expression.Convert(property, typeof(object));
    return Expression.Lambda<Func<TDocument, object>>(castResult, parameter);
}

query = query.SortByDescending(GetPropertyExpression<Items>(sortBy));

As far as Mongo is concerned, this is no different to having written query = query.SortByDescending(i => i.Name);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.