-2

I have a list which I am currently sorting manually by using .OrderBy:

var newList = pouchList
    .OrderBy(x => x.ID3Val)
    .ThenBy(x => x.ID4Val == "LATE")
    .ThenBy(x => x.ID4Val == "BED")
    .ThenBy(x => x.ID4Val == "TEA")
    .ThenBy(x => x.ID4Val == "LNCH")
    .ThenBy(x => x.ID4Val == "MORN")
    .ToList();

What I would like to do is have the parameters to which the list is ordered by in an array ie:

[ "LATE", "BED", "TEA", "LNCH", "MORN" ]

so that I can change the array and have the list sorted dynamically using these parameters.

Does anyone know if this is possible?

RagtimeWilly
  • 5,265
  • 3
  • 25
  • 41
Brownd92
  • 75
  • 1
  • 11
  • 2
    It would be awesome if you could provide a [mcve] with sample inputs and expected results based on those sample inputs. This makes it easier for us to help you, since we don't need to waste time guesses what the classes and data look like. – mjwills Nov 13 '18 at 22:21
  • The parameter to `OrderBy` (and to `ThenBy`) is a `KeySelector`. You use it to select which column you want to sort by. All of your `ThenBy` methods are given a lambda expression that evaluates to a Boolean. What you want to do is add an `IComparer` implementation that does your comparisons and figures out your sort order (https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.icomparer-1). If you augment your question with enough information (in particular, the contents of the array you are starting with), I'll provide an answer. – Flydog57 Nov 13 '18 at 22:27
  • By the way, as this was getting marked as a dup, I prepared an answer for you. The answer involved creating a custom `IComparer` that used an `enum` to establish sort order. The enum looked like `public enum PouchOrder { LATE, BED, TEA, LNCH, MORN, BAD, }`. Anything that didn't parse as an enum of that type (using `enum.TryParse` got marked as "BAD" and sorted last. – Flydog57 Nov 13 '18 at 22:56

1 Answers1

0

Each of the .OrderBy() and .ThenBy() calls will return a IOrderedEnumerable object. You can store the result of OrderBy() in a variable, then iterate over your array of values and replace that variable with a result of each ThenBy() call. Something like that:

var orderingList = new string[] {"LATE", "BED", "TEA", "LNCH", "MORN"};
var newEnumerable = pouchList.OrderBy(x => x.ID3Val);
for(int i = 0; i < orderingList.Length; i++)
{
    newList = newList.ThenBy(x => x.ID4Val == orderingList[i]);
}
var newList = newEnumerable.ToList();

Here's a MSDN page for reference: ThenBy

Szab
  • 1,263
  • 8
  • 18