我已经在下面写了选择排序方法。我想保留一般的代码,因为这是一个学校练习,但我知道有更正确的方法来做到这一点,就像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;
}
}
}
你可以使用LINQ的,它会进行排序:
你会然后用lambda表达式消费这用简单的标准给你列表 –
嗨,我还是个新手。我稍后离开Linq。我仍然在学习基础知识。 – Max
Linq是你对这个“排序”事物的朋友:-p http://stackoverflow.com/questions/722868/sorting-a-list-using-lambda-linq-to-objects – ManoDestra