Home > Blockchain >  C# Ordering Collection by Unknown Properties
C# Ordering Collection by Unknown Properties

Time:01-17

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?

CodePudding user response:

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.

  • Related