Sort one List<> based on another

前端 未结 4 1140
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 23:22

Say I have

List ages  = new List() { 8, 5, 3, 9, 2, 1, 7 };
List marks = new List() { 12, 17, 08, 15, 19, 02, 11          


        
4条回答
  •  清歌不尽
    2020-12-07 00:03

    There's no framework method to do this with List, but if you don't mind putting the data into two arrays, you can use one of the Array.Sort() overloads that takes two arrays as arguments. The first array is the keys, and the second is the values, so your code might look like this (leaving aside the step of getting arrays from the lists):

    Array.Sort(ages, marks);
    

    The specifics of getting the values into arrays and then back into lists would depend, among other things, on whether you need to end up with the same list sorted appropriately or whether it's okay to return a new list with the data in the desired order.

提交回复
热议问题