In C#, what is the best way to sort a list of objects by a string property and get correct order?

前端 未结 5 799
不知归路
不知归路 2020-12-22 02:49

I have a list of \"Issue\" objects and i want to sort them by the \"Priority\" field.

The issue is that \"Priority\" is a string name like \"HIGH\", \"MEDIUM\" so i

5条回答
  •  生来不讨喜
    2020-12-22 03:31

    The easiest way would probably be like:

    private static int MapPriority(string priority)
    {
      switch(priority.ToUpperInvariant())//skip the case bit if safe
      {
        case "HIGH":
          return 1;
        case "MEDIUM":
          return 2;
        case "LOW":
          return 3;
        default:
          return 4;
      }
    }
    
    var sorted = someCollection.OrderBy(i => MapPriority(i.PriorityProperty));
    

    With a db-backed form you'll need a function in the DB you can call into. This is in-memory only.

    With lots of possible values, I'd base it on a dictionary rather than hand-code. I'd hand-code for three as in this case though (unless the values used could change, a further complication making dictionary-based approaches the only way).

    If sorting a serious number of such items, or calling this a lot, I'd go with an IComparer implementation, or have the item itself implement IComparable.

提交回复
热议问题