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

前端 未结 5 815
不知归路
不知归路 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:51

    You could, in this specific case, also use Linq's OrderBy method:

    var sortedList = issueList.OrderBy(i=>
                        i.Priority == "HIGH" 
                           ? 1 
                           : i.Priority == "MEDIUM" 
                              ? 2 
                              : 3).ToList();
    

    As a one-liner this wouldn't be too bad. You could also put the strings into an array, list or Dictionary in the order you want them sorted (or containing the sort order as the Value in the case of the Dictionary).

    The one downside of using OrderBy is that it doesn't affect the source List unless you tell it to by reassigning the List to the result. In all cases, it will create two additional collections; an internally-used array or list within OrderBy (sorts have to have knowledge of the entire collection they're sorting) and the List produced by ToList(). So, this will require O(2N) additional memory, while List.Sort() could be in-place (not sure if it actually is, but it does use QuickSort which is normally in-place).

提交回复
热议问题