Method for sorting a list in C#
本问题已经有最佳答案,请猛点这里访问。
我在下面编写了选择排序方法。我想保留代码,因为它是学校练习,但我知道有更多正确的方法可以做到这一点,就像使用LINQ一样。除此之外,它只对PersonalNumber属性进行排序,而且工作得很好。我可以看到错误在哪里:
1 2 3 | temp = list[i].PersonalNumber; list[i].PersonalNumber = list[posMin].PersonalNumber; list[posMin].PersonalNumber = temp; |
是否有任何方法可以对列表中每个索引包含的所有属性进行排序?还是我必须为每个属性编写上述代码?总共有三个属性。
完整方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static void SelectionSort(List<Person> list) { // With this method the Person list is sorted in ascending order. //posMin is short for position of min int posMin, temp; for (int i = 0; i < list.Count - 1; i++) { posMin = i;//Set posMin to the current index of array for (int j = i + 1; j < list.Count; j++) { if (list[j].PersonalNumber < list[posMin].PersonalNumber) { //posMin will keep track of the index that min is in, this is needed when a swap happens posMin = j; } } //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur if (posMin != i) { temp = list[i].PersonalNumber; list[i].PersonalNumber = list[posMin].PersonalNumber; list[posMin].PersonalNumber = temp; } } } |
这绝对不是你应该手动做的事情(除非你正在训练你的算法技能)。这将使代码更复杂,更难维护。
只放:
1 | using System.Linq; |
这样做:
1 | var sorted = list.OrderByDescending(x => x.PersonalNumber).ToList(); |
你用不着做林克忍者。我也强烈建议开始使用它。我认为你可以同意,它很容易阅读,而且很明显它在做什么。
啊,如果你想升序排序,只需使用.orderby而不是.orderby降序。
如果要对列表进行排序,只需将
1 | list.Sort((x, y) => x.PersonalNumber.CompareTo(y.PersonalNumber)); |
要按降序排序,请添加
1 | list.Sort((x, y) => -x.PersonalNumber.CompareTo(y.PersonalNumber)); |
对于大多数场景,您应该使用其中一个内置功能进行排序,例如
可以将键选择器函数作为方法的第二个参数引入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public static void SelectionSort<TSource, TKey>( List<TSource> list, Func<TSource, TKey> keySelector) { // With this method the list is sorted in ascending order. //posMin is short for position of min int posMin; for (int i = 0; i < list.Count - 1; i++) { posMin = i;//Set posMin to the current index of array for (int j = i + 1; j < list.Count; j++) { if (keySelector(list[j]) < keySelector(list[posMin])) { //posMin will keep track of the index that min is in, this is needed when a swap happens posMin = j; } } //if pos_min no longer equals i than a smaller value must have been found, so a swap must occur TSource temp; if (posMin != i) { temp = list[i]; list[i] = list[posMin]; list[posMin] = temp; } } } |
然后您将使用lambda表达式来使用它:
1 | SelectionSort(persons, (Person p) => p.PersonalNumber); |