Sort one List<> based on another

前端 未结 4 1142
爱一瞬间的悲伤
爱一瞬间的悲伤 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:02

    To sort one list the way you want you actually need to somehow keep references from items in first list to they weight/keys in the second list. No existing methods do that as you can't easily associate metadata with arbitrary values (i.e. if first list is list of int as in your case there is nothing to map to keys in second list). Your only reasonable option is to sort 2 lists at the same time and make association by index - again no existing classes to help.

    It may be much easier to use solution that you reject. I.e. simply Zip and OrderBy, than recreate first list:

    ages = ages
      .Zip(marks, (a,m)=> new {age = a; mark = m;})
      .OrderBy(v => v.mark)
      .Select(v=>v.age)
      .ToList();
    

    Note (courtesy of phoog): if you need to do this type of sorting with Array there is Array.Sort that allows exactly this operatiion (see phoog's answer for details).

提交回复
热议问题