0

How can I order a list of objects by unknown number of values? Using LINQ it will something like this:

var myNewCollection = myCollection.OrderBy(c => c.Id).ThenBy(c => c.Name).ThenBy(c => c.Years).ToList();

And I have a list of 11 properties the user can sort by. When I don't know how many fields the use will select, how can I build my expression in this instance?

1

1 Answer 1

1

Add nuget package ... System.Linq.Dynamic.Core

This is the site with the documentation ... https://dynamic-linq.net/

You need to build a string which looks something like this ... Id ASC, Name DESC, Years ASC ... as per the documentation, or, straight sorting without the direction, e.g. Id, Name, Years. Then simply call the OrderBy method (https://dynamic-linq.net/basic-simple-query#ordering-results) ...

var sortBy = "Id, Name, Years";

var result = DynamicQueryableExtensions.OrderBy(data.AsQueryable(), sortBy).ToList();

If required, you'll need to do the fancy footwork to make the selection the user sees more useful than the name of your fields.

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.