SortedList就是按照key来排序的,如果你想按value来排序的话干脆把key=value来做好了,
但是Key的值是不允许重复的,也就是说如果value值有重复,那么排序后的结果中就只有一个该value值(重复的被去掉)对SortedList 初始化后,使用foreach遍历该SortedList 得到的自然是排好序后的结果SortedList mySortedList = new SortedList(); mySortedList["张三"]="我是张三"; mySortedList["李四"]="我是李四"; mySortedList["王五"]="我是王五"; mySortedList["赵六"]="我是赵六"; foreach (DictionaryEntry Item in mySortedList) { ListItem newListItem = new ListItem(); newListItem.Text = Item.Key.ToString(); newListItem.Value = Item.Value.ToString(); myDropDownList.Items.Add(newListItem);
}
但是Key的值是不允许重复的,也就是说如果value值有重复,那么排序后的结果中就只有一个该value值(重复的被去掉)对SortedList 初始化后,使用foreach遍历该SortedList 得到的自然是排好序后的结果SortedList mySortedList = new SortedList(); mySortedList["张三"]="我是张三"; mySortedList["李四"]="我是李四"; mySortedList["王五"]="我是王五"; mySortedList["赵六"]="我是赵六"; foreach (DictionaryEntry Item in mySortedList) { ListItem newListItem = new ListItem(); newListItem.Text = Item.Key.ToString(); newListItem.Value = Item.Value.ToString(); myDropDownList.Items.Add(newListItem);
}
解决方案 »
- 关于WPF中的Usercontrol的一些疑问
- 尝试读取或写入受保护的内存。这通常指示其他内存已损坏??
- c#中Repeater取字段问题
- (有空聊聊,没空接分!)这1000块的工资,老子不要也罢。我在一家软件公司的经历。绝对真实。(斑主留情,我自已转)
- 我有两个窗体,一个是设置为主窗体(为容器),一个是普通窗体,如何让普通窗体在主窗体中显示,成为主窗体中的子窗体??
- 菜鸟求救
- 请大家帮忙,如何在 DataTable 中使用 "SELECT DISTINCT id FROM xxx" 这样的查询。
- DataTable的Copy()和Clone()引起“该行已经属于另一个表”的问题
- DataGrid问题。
- WPF,DataGrid数据绑定不是双向绑定也能更新?
- 如何打印一个winform窗体?
- 图片数据恢复问题。500分相送
public class clsSort:IComparer
{
public string Key;
public int Value; #region IComparer 成员 public int Compare(object x, object y)
{
// TODO: 添加 clsSort.Compare 实现
clsSort objX=x as clsSort;
clsSort objY=y as clsSort; if(objX.Value>objY.Value)
return 1;
if(objX.Value<objY.Value)
return -1;
return 0;
} #endregion
}//排序测试
private void btnSortTest_Click(object sender, System.EventArgs e)
{
ArrayList arrList=new ArrayList(); clsSort cls=new clsSort();
cls.Key="c";
cls.Value=12;
arrList.Add(cls); cls=new clsSort();
cls.Key="b";
cls.Value=23;
arrList.Add(cls); cls=new clsSort();
cls.Key="d";
cls.Value=120;
arrList.Add(cls); cls=new clsSort();
cls.Key="g";
cls.Value=2;
arrList.Add(cls); cls=new clsSort();
cls.Key="x";
cls.Value=199;
arrList.Add(cls);
arrList.Sort(new clsSort()); for(int i=0;i<arrList.Count;i++)
{
clsSort obj=(clsSort)arrList[i];
Console.WriteLine("Key={0}, Value={1}",obj.Key,obj.Value);
}
}
实现IComparer接口写一个比较类