Sort a list according to another list

后端 未结 5 1632
慢半拍i
慢半拍i 2020-12-21 12:29

I have a list1 like this :

{A,B,C,D,E,F}

I have another list2 that list2 count is equal with l

5条回答
  •  暖寄归人
    2020-12-21 12:46

    You can do this directly if you use an array instead of a list:

    string[] list1 = 
    {
        "A", "B", "C", "D", "E", "F"
    };
    
    int[] list2 = 
    {
        50, 100, 14, 57, 48, 94
    };
    
    Array.Sort(list2, list1);
    
    Console.WriteLine(string.Join(", ", list1)); // C, E, A, D, F, B
    

    The Array.Sort(Array keys, Array items) method is provided for this exact purpose.

    Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

    Sadly, there is no equivalent for List.

提交回复
热议问题