特殊字符订购问题

时间:2017-03-21 22:44:34

标签: c# linq

以下订购工作

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();

但是如果我按如下方式更改PackageOrder字符串,那么它就没有正确排序。

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

1 个答案:

答案 0 :(得分:3)

假设您不需要订单功能是动态的:

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;
}

调用
var list = mail.Package
  .OrderBy(p => OrderKeyGenerator(p.Name))
  .ToList();