-4

The following ordering works

private static string[] PackageOrder = new[] { "KK", "AB", "BC", "DD", "FV", "ER", "PP", "WW" };

var list =  mail.Package.OrderBy(p => Array.IndexOf(PackageOrder, p.Name)).ToList();

but if I change the PackageOrder string as follows, then it does not order correctly.

private static string[] PackageOrder = new[] { "KK %", "AB", "AB art", "DD %", "FV", "ER", "PP", "WW" };
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 1
    Probably because `IndexOf` is not finding the strings and returning -1. Have you tried debugging it?? Remember it's case sensitive. If `Package` is a long list, I suggest you use a `Dictionary` instead in order to avoid a huge amount of calls to `IndexOf`. – Andrew Mar 21 '17 at 22:47
  • 1
    Please read [ask] and provide a [mcve]. For what input does and doesn't this work? What do you expect `"KK %"` to do? – CodeCaster Mar 21 '17 at 22:56

1 Answers1

2

Assuming you don't need the order function to be dynamic:

private static int OrderKeyGenerator (string packageName)
{
    return
      packageName.StartsWith("KK ") ? 1:
      packageName == "AB" ? 2:
      packageName == "AB art" ? 3:
      packageName.StartsWith("DD ") ? 4:
      packageName == "FV" ? 5:
      packageName == "ER" ? 6:
      packageName == "PW" ? 7:
      packagename == "WW" ? 8:
      9;
}

called with

var list = mail.Package
  .OrderBy(p => OrderKeyGenerator(p.Name))
  .ToList();
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • What does this do different from ordering by `Array.IndexOf`? – CodeCaster Mar 21 '17 at 22:55
  • 1
    IndexOf won't find the wildcard matches. I've replaced the TSQL style wildcards with calls to string.StartsWith – Amy B Mar 21 '17 at 22:56
  • 1
    Of course, but that's assuming the OP expects such characters in strings to magically work like SQL wildcard matches, which I find a stretch. I meant if you could explain that misconception in your answer if you believe that to be the case. Do note that the OP also asked [Custom Ordering in C#](http://stackoverflow.com/questions/42938201/custom-ordering-in-c-sharp) an hour ago, where they do use `a.Name == "KK %"` and claim it works. – CodeCaster Mar 21 '17 at 23:02