2016-04-07 56 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);