排序算法-C# [英] Sorting Algorithm - C#
问题描述
我有以下未排序列表:
List<string> myUnsortedList = New List<string>();
myUnsortedList.Add("Alpha");
myUnsortedList.Add("(avg) Alpha");
myUnsortedList.Add("Zeta");
myUnsortedList.Add("Beta");
myUnsortedList.Add("(avg) Beta");
myUnsortedList.Add("(avg) Zeta");
我想按字母降序对列表进行排序,然后在正常值后紧跟(avg)来获取值:
I want to sort the list descending alphabetical order, then have the value with (avg) right after the normal value:
最终结果:Zeta,(平均)Zeta,Beta,(平均)Beta,Alpha,(平均)Alpha
Final Result: Zeta, (avg) Zeta, Beta, (avg) Beta, Alpha, (avg) Alpha
我的应用程序是用C#
编写的,我想使用LINQ
完成排序
My application is written in C#
and I want to use LINQ
to accomplish the sorting
推荐答案
假设(avg)"是唯一的特殊前缀,这应该可以满足您的需求
This should work ok for what you need, assuming "(avg)" is the only special prefix
这将排序所有不包括(avg)"的字符串,然后按字符串长度排序,这样,带有(avg)"前缀的字符串将排在不带字符串的后面
This will order all the stings descending not including the "(avg) " then it will order by the strings length this way the string with the "(avg)" prefix will come after the one without
var result = myUnsortedList.OrderByDescending(x => x.Replace("(avg) ", "")).ThenBy(x => x.Length);
最终结果:
- Zeta
- (avg)Zeta
- 测试版
- (avg)Beta
- Alpha
- (avg)Alpha
这篇关于排序算法-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!