0

I have a List<T> and now i have to show a page to user on which every of the fields inside object are shown with a checkbox.

Now if user checks any of them, or check all of them, or lets say select's none of them, how do I order my list accordingly?

There are some 8 fields out of which user can select any combination, so the data inside the list should be accordingly ordered.

I am currently using List<> method OrderBy().

Any help would be appreciated.

here is How i am using the method but in my case there are 8 fields now how many combinations can becomes of them I cannot put so many ifs there.

SortedList = list.OrderBy(x => x.QuantityDelivered).ThenBy(x => x.Quantity).ToList();

khalid khan
  • 135
  • 1
  • 9
  • Please share what have you tried. It would be easier to help if you've shown your code. – BartoszKP Oct 01 '13 at 10:01
  • 1
    Just FYI, `OrderBy` is an extension method for `IEnumerable` and isn't directly part of `List`. I would personally do this using a custom `IComparer` definition that you can then provide in conjunction with calling `Sort` on the list. The implementation of the `IComparer` interface can then take into account the fields that are selected by the user. – Adam Houldsworth Oct 01 '13 at 10:03
  • 2
    http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet – Sriram Sakthivel Oct 01 '13 at 10:05
  • I have added the code that i am trying right now. – khalid khan Oct 01 '13 at 10:08
  • well +Sriram Sakthivel, I m sorry! the Answer to that Question is just over my head i don't quite Understand that and I am not that Experienced in c# so perhap's some simple solution If Possible from the Expert guys out there. though thank you already. – khalid khan Oct 01 '13 at 10:32

1 Answers1

1

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.

Yaakov Ellis
  • 38,048
  • 29
  • 119
  • 167