0

I have the following code to construct a SORT query inside a foreach loop, however my problem is this will replace my old sort descriptor with latest one.

SearchDescriptor<MyDTO> nQuery = new SearchDescriptor<MyDTO>();
foreach (var sort in criteria.SortQuery.OrderBy(o => o.SortPreference))
                {
                  nQuery=  nQuery.Sort(s => s.Field(sort.SortName, sort.SortOrder));
                }

How to achieve this inside a ForEach

1 Answer 1

4

You can do this by

var sortDescriptor = new SortDescriptor<Document>();

foreach (var sort in sortCollection)
{
    SortOrder sortOrder;
    var tryParse = Enum.TryParse(sort.Order, out sortOrder);
    if(!tryParse) up to you how you are going to handle incorrect sort order
    sortDescriptor.Field(sort.FieldName, sortOrder);
}

client.Search<Document>(s => s.Size(0).Sort(sort => sortDescriptor));

Hope it helps.

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

1 Comment

Thanks Indeed I went with this :)

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.