根据预排序列表对列表进行排序 [英] Sort a List based on a Pre-Sorted List
问题描述
如何基于预排序列表对列表进行排序.
How can I sort a list based on a pre-sorted list.
我有一个已排序的列表.说,我的排序列表是
I have a list which is already sorted. Say, my sorted list is
{"Junior Developer", "Developer", "Senior Developer", "Project Lead"}
现在,我想按与上述列表相同的顺序对上述列表的任何子集进行排序.也就是说,如果我有输入
Now, I want to sort any subset of the above list in the same order as the above list. That is, if I have as input
{"Developer", "Junior Developer"}
,我希望输出为{"Junior Developer", "Developer"}
如果输入为{"Project Lead", "Junior Developer", "Developer"}
,我希望输出为
If the input is {"Project Lead", "Junior Developer", "Developer"}
, I want the output as
{"Junior Developer", "Developer", "Project Lead"}.
我怎么能达到同样的目的?
How can I achieve the same?
推荐答案
最简单的方法是使用LINQ的.OrderBy
扩展方法以及预排序集合的IndexOf
方法(或等效方法).这里的想法是使用一个不同的值作为排序键"进行排序(这很有用,因为我们经常希望根据对象的属性之一对对象进行排序).
The simplest way would be to use LINQ's .OrderBy
extension method, along with the IndexOf
method (or equivalent) of your pre-sorted collection. The idea here is to sort using a different value as the "sort key" (this is quite useful, since often we'll want to sort objects based on one of their properties).
var sorted = listToSort.OrderBy(s => listPreSorted.IndexOf(s)).ToList();
这是一个数组示例: http://ideone.com/7oshhZ
请注意,如果您的列表非常大,这可能会很慢,因为目标列表中的每个项目都必须在预先排序的集合中依次查找(O(N * M)
,其中N
是目标列表的长度,M
是预排序列表的长度.
Note that if your lists are very large, this will likely be slow, since each item in your target list has to be sequentially looked up in your pre-sorted collection (O(N * M)
, where N
is the length of the target list, and M
is the length of the pre-sorted list).
要克服此限制,您可以生成一个将预排序列表的项目映射到其索引的查找,然后在.OrderBy
中使用此查找(运行时为O(N + M)
,您可以重新运行-如果需要,请使用查找):
To overcome this limitation, you could generate a lookup mapping the items of your pre-sorted list to their indices, then use this lookup in your .OrderBy
(this would have a runtime of O(N + M)
, and you could re-use the lookup if needed):
var preSortedLookup =
listPreSorted.Select((v, i) => new { Key = v, Value = i })
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var sorted = listToSort.OrderBy(s => preSortedLookup[s]).ToList();
这篇关于根据预排序列表对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!