scr*_*rot 1 .net c# sorting list
例外:无法比较数组中的两个元素.
private void assignNames(DropDownList ddl, Hashtable names)
{
List<ListItem> nameList = new List<ListItem>();
if (ddl != null)
{
ddl.ClearSelection();
ddl.Items.Add(new ListItem("Select Author"));
foreach (string key in names.Keys)
{
nameList.Add(new ListItem(names[key].ToString(), key));
}
nameList.Sort();
}
Run Code Online (Sandbox Code Playgroud)
那么如何使用Sort()来比较"名称"而不是卡在键上?
bdu*_*kes 11
提供一个Comparison<T>
指示List
如何对项目进行排序.
nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {
return thisItem.Text.CompareTo(otherItem.Text);
});
Run Code Online (Sandbox Code Playgroud)
您可能还希望检查是否null
完整,除非您已经知道不会有任何内容,例如在这种情况下.