2016-04-07 55 views
0

我已经在下面写了选择排序方法。我想保留一般的代码,因为这是一个学校练习,但我知道有更正确的方法来做到这一点,就像Linq一样。 它运作良好,除此之外它只对属性PersonalNumber进行排序。我能看到的错误是:在C中排序列表的方法#

temp = list[i].PersonalNumber; 
list[i].PersonalNumber = list[posMin].PersonalNumber; 
list[posMin].PersonalNumber = temp; 

有什么办法来排序包含的所有列表中的每个索引的属性?或者我必须为每个属性编写上述代码?总共有三个属性。

全部方法:

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; 
     } 
    } 
} 
+3

你可以使用LINQ的,它会进行排序:

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表达式消费这用简单的标准给你列表 –

+0

嗨,我还是个新手。我稍后离开Linq。我仍然在学习基础知识。 – Max

+3

Linq是你对这个“排序”事物的朋友:-p http://stackoverflow.com/questions/722868/sorting-a-list-using-lambda-linq-to-objects – ManoDestra

回答

1

这绝对不是你应该做手工(除非你训练你的算法学技能:))。它会使你的代码更加复杂和难以维护。

只要把:

using System.Linq; 

,并做到这一点:

var sorted = list.OrderByDescending(x => x.PersonalNumber).ToList(); 

你不需要是Linq的忍者使用它。我也强烈建议开始使用它。我认为你可以认同它很容易阅读,而且很明显它在做什么。

啊,如果你想排序升序,只需使用.OrderBy而不是.OrderByDescending。

+0

嗨,谢谢你的回答。我想保留原来的编码,因为这是一个学校练习,但我会和Linq一起去。 – Max

0

如果你想在地方排序列表,只是把Sort

list.Sort((x, y) => x.PersonalNumber.CompareTo(y.PersonalNumber)); 

要按降序顺序,添加-

list.Sort((x, y) => -x.PersonalNumber.CompareTo(y.PersonalNumber)); 
0

对于大多数情况下,你应该使用其中一种内置功能进行分类,如List<T>.SortEnumerable.OrderBy。我假设你想保留你自己的排序算法实现。

您可以引入一键选择功能作为第二个参数,以你的方法:

SelectionSort(persons, (Person p) => p.PersonalNumber);