Sort a list according to another list

后端 未结 5 1626
慢半拍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:44

    Why not use a sorted dictionary?

    var list1 = new List<int> { 50, 100, 14, 57, 48, 94 }
    var list2 = new List<string> { "A", "B", "C", "D", "E", "F" };
    var dict = new SortedDictionary<int, string>();
    
    for (int i = 0; i < list1.Count; i++)
    {
       dict.Add(list1[i], list2[i]);
    }
    

    You'll now be able to access the values in the correct order.

    0 讨论(0)
  • 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<T>.

    0 讨论(0)
  • 2020-12-21 12:52

    Try this:

    int index = 0;
    list1 = list1.OrderBy(d => list2[index++]).ToList();
    

    It should produce the expected result given the following two lists:

    List<string> list1 = new List<string> { "A", "B", "C", "D", "E", "F" };
    List<int> list2 = new List<int> { 50, 100, 14, 57, 48, 94 };
    
    0 讨论(0)
  • 2020-12-21 12:58

    Try this:

    docs = docs.OrderBy(d => docsIds.IndexOf(d.Id)).ToList();
    

    should give the expected result.

    0 讨论(0)
  • 2020-12-21 13:04

    You could use Enumerable.Zip to combine them, then OrderBy to order

    Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

    var first = new List<char>() { 'A', 'B', 'C', 'D', 'E', 'F' };
    
    var second = new List<double>() { 50, 100, 14, 57, 48, 94 };
    
    var results = first.Zip(second, (f, s) => (first: f, second: s))
                       .OrderBy(x => x.second)
                       .Select(x => x.first);
    
    Console.WriteLine(string.Join(", ", results ));
    

    Output

    C, E, A, D, F, B
    
    0 讨论(0)
提交回复
热议问题