w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Custom Order By, How do I let User to select fields on which to Order A List

Assuming that you are able to determine in your code which field was clicked for sorting:

IEnumerable<T> items = // code to get initial data, 
                       // set to be an IEnumerable. with default sort
applied
List<string> sortFields = // code to get the sort fields into a list,
                          // in order of selection
bool isFirst = true;

foreach (string sortField in sortFields) {
  switch (sortField )
  {
      case "field1":
          if (isFirst) {
            items = items.OrderBy(x => x.Field1);
          } else {
            items = items.ThenBy(x => x.Field1);
          }
          break;
      case "field2":
          if (isFirst) {
            items = items.OrderBy(x => x.Field2);
          } else {
            items = items.ThenBy(x => x.Field2);
          }
          break;
      // perform for all fields
  }
  isFirst = false
}

var listOfItems = items.ToList();

The list is now sorted by the selected field, usable in whatever way you see fit.

Might be safer to convert the sort fields to an enum, and switch on that to avoid errors with copying strings.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.