Sunday, 14 August 2016

Method for sorting a list in C#





I've written the the selection sort method beneath. I would like to retain the code in general as it's a school exercise, but I understand that there are more correct ways to do it, as with Linq.
It works well besides that it only sorts the property PersonalNumber. I can see where the error is the following:



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


Is there any way to sort all of the properties contained for each index in the list? Or do I have to write the above code for each property? There are three properties in total.




Full method:



public static void SelectionSort(List 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;

}
}
}

Answer



If you want to sort list in place, just put Sort:



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



To sort in descending order, add -:



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...