简体   繁体   English

在特定位置后,用lambda按字母顺序对列表进行排序

[英]Sorting a list alphabetically with lambda after a certain position

Given a list with three elements that must stay at the top always: 给定一个包含三个元素的列表,这些元素必须始终位于顶部:

Stay@Top1
Stay@Top2
Stay@Top3
Chicken
Bull
Zebra
Elephant
Hippo

Using lamdba expression, how can you sort this list alphabetically starting with "Chicken", and keeping the first three elements at the top? 使用lamdba表达式,如何从“ Chicken”开始按字母顺序对列表进行排序,并将前三个元素保持在顶部?

Thanks ahead of time for any hints! 提前感谢您的任何提示!

取前三个项目,然后与排序后的余数合并。

lst.Take(3).Concat(lst.Skip(3).OrderBy(s=>s);

尝试使用此:

list.Take(3).Concat(list.Skip (3).OrderBy (x => x.Name))

Given a List<T> where you wish to sort it but keep the first three elements at the start, you can use the overload of List<T>.Sort(int index, int count, IComparer<T> comparer) which lets you specify the range of elements to sort. 给定一个List<T> ,您希望在其中进行排序,但将前三个元素保留在开头,则可以使用List<T>.Sort(int index, int count, IComparer<T> comparer)的重载。指定要排序的元素范围。

So you could do (assuming List<string> ): 所以你可以做(​​假设List<string> ):

lst.Sort(3, lst.Length - 3, Comparer<string>.Default);

This doesn't use a lambda like you asked for - but I don't see why you need to use a lambda. 它不使用您所要求的lambda-但我不明白为什么需要使用lambda。 ;) ;)

An in-place sort is going to be much more efficient, if you can use it. 如果可以的话,就地排序将更加高​​效。

var final = lst.Take(3).ToList(); ;

var sortedSet = lst.Skip(3).OrderBy(x => x);

final.AddRange(sortedSet);

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

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