對集合排序的三種方式

2022-01-18 23:39:27 字數 1821 閱讀 2115

對集合排序,可能最先想到的是使用orderby方法。

class program
console.readkey();
}
private static list<

student

> getstudents()

,
new student(),
new student()
};
}
}
public class student
public string name
public int age
public int score
}

以上,orderby返回的型別是ienumerable。

如果想使用list的sort方法,就需要讓student實現icomparable介面。

class program
console.readkey();
}
private static list<

student

> getstudents()

,
new student(),
new student()
};
}
}
public class student : icomparable<

student

>

public string name
public int age
public int score
public int compareto(student other)
}

讓student實現icomparable介面固然很好,如果student是乙個密封類,我們無法讓其實現icomparable介面呢?不用擔心,sort方法提供了乙個過載,可以接收icomparer介面型別。

class program
console.readkey();
}
private static list<

student

> getstudents()

,
new student(),
new student()
};
}
}
public class student
public string name
public int age
public int score
}
public class studentsorter : icomparer<

student

>

}

綜上,如果我們想對乙個集合排序,大致有三種方式:

1、使用orderby方法,返回ienumerable型別。

2、讓集合元素實現icomparable介面,再使用sort方法,返回void。

3、集合元素不實現icomparable介面,針對集合元素型別寫乙個實現icomparer介面的類,把該類例項作為sort方法的引數。

Collection集合的三種遍歷方式

public class testiterator suppresswarnings all test public void test4 for string string arr suppresswarnings all test public void test3 suppresswarnin...

對xml的三種解析方式

解析器在解析xml文件的時候 會把文件內容寫入到記憶體中 如果實現了文件節點的增刪改後 就必須運用 transformer transformer transforme ctory.newinstance newtransformer transformer.transform new domsou...

list排序的三種實現方式

用了一段時間的gridview,對gridview實現的排序功能比較好奇,而且利用c 自帶的排序方法只能對某乙個字段進行排序,今天demo了一下,總結了三種對list排序的方法,並實現動態傳遞欄位名對list進行排序。首先先介紹一下平時最常用的幾種排序方法。第一種 實體類實現icomparable ...