简体   繁体   English

如何使用 Linq 使用另一个列表的值对列表进行排序

[英]How to sort a list with the values of another list with Linq

I have a list of parameters:我有一个参数列表:

List<double> parameters = new List<double>() { 3.56, 8.9, 1.7, 0.5, 4.69 };

And a list of generic objects:以及通用对象列表:

List<object> objects= new List<object>() { objA, objB, objC, objD, objE };

How can I sort "objects" list accordingly with the sorting of "parameters" list?如何根据“参数”列表的排序对“对象”列表进行排序?

Although you accepted an answer, it's still fun to show a not a well-known method, but faster than any and a one-liner.虽然你接受了一个答案,但展示一种不知名的方法仍然很有趣,但比任何一种都快,而且是单行的。 But you have to start with arrays:但是你必须从数组开始:

var parameters = new [] { 3.56, 8.9, 1.7, 0.5, 4.69 };
var objects = new [] { "objA", "objB", "objC", "objD", "objE" };

Array.Sort(parameters, objects);

Now objects is persistently sorted according to the sort order of parameters :现在objects根据parameters的排序顺序持久排序:

objD
objC
objA
objE
objB

You can use the Linq function OrderBy to sort the objects using their respective index in the parameters list as a key.您可以使用 Linq 函数OrderBy使用参数列表中的相应索引作为键对对象进行排序。

List<double> parameters = new List<double>() { 3.56, 8.9, 1.7, 0.5, 4.69 };
List<object> objects = new List<object>() { objA, objB, objC, objD, objE };

objects = objects.OrderBy(x => parameters[objects.IndexOf(x)]).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM