最近在写一个功能是,在ListView中填充了多条记录,要求点击标题头时,对记录进行排序。
各个列中,有数值型的,如序号,有string型的,还有时间类型的。
时间类型的其实可以作为string来比较。
所以我们就需要两种类型的比较:数值型,string型。
于是想说可以传进去类型参数比较。
排序法用的是二分法,基本的二分法排序如下:对一个int型的数组进行排序
/// <summary>
/// 二分法排序
/// </summary>
/// <param name="arr"></param>
public void Sort(int[] arr)
{
for (int id = 0; id < arr.Length; id++)
{
int start = 0;
int end = id - 1;
int midle = 0;
// 找位置
while (start <= end)
{
midle = (start + end) / 2;
int tmp = arr[midle];
if (tmp < arr[id])
{
start = midle + 1;
}
else
{
end = midle - 1;
}
}
// 调整位置
for (int j = id - 1; j > end; j--)
{
arr[j + 1] = arr[j];
}
arr[end + 1] = arr[id];
}
}
在我要的功能中,则可以构造一个键值对,按键值进行排序,如下:
public class SortKeyValuePairList<Tkey, Tvalue>
where Tkey : IComparable<Tkey>
{
/// <summary>
/// 按键值二分法排序
/// </summary>
/// <param name="tmpPair"></param>
/// <param name="tmpList"></param>
public static void SortKeyValuePair(/*KeyValuePair<Tkey, Tvalue> pPair, */ref List<KeyValuePair<Tkey, Tvalue>> pList, bool IsAsc = true)
{
if (null == pList)
{ pList = new List<KeyValuePair<Tkey, Tvalue>>(); }
for (int index = 0; index < pList.Count; index++)
{
KeyValuePair<Tkey, Tvalue> pPair = pList[index];
Tkey tmpkey = pPair.Key;
Tvalue tmpvalue = pPair.Value;
int start = 0;
int end = index - 1;
int midle = 0;
// 找位置
while (start <= end)
{
midle = (end + start) / 2;
KeyValuePair<Tkey, Tvalue> tmppair = pList[midle];
int compareresult = pPair.Key.CompareTo(tmppair.Key);
if (compareresult > 0)
{
start = midle + 1;
}
else
{
end = midle - 1;
}
}
// 放到找到的位置
for (int j = index - 1; j > end; j--)
{
pList[j + 1] = pList[j];
}
pList[end + 1] = pPair;
}
// 倒序排序
List<KeyValuePair<Tkey, Tvalue>> pListtmp = new List<KeyValuePair<Tkey, Tvalue>>();
if (!IsAsc)
{
for (int id = pList.Count - 1; id >= 0; id--)
{
pListtmp.Add(pList[id]);
}
pList.Clear();
pList = pListtmp;
}
}
}
如何使用:
定义一个List:
List<KeyValuePair<string, ListViewItem>> SortedKeyValuePair = new List<KeyValuePair<string, ListViewItem>>();
构造键值对:
string value = listView_hisNotice.Items[id].SubItems[index].Text.Trim();
KeyValuePair<string, ListViewItem> tmpkeyvalue = new KeyValuePair<string, ListViewItem>(value, listView_hisNotice.Items[id]);
for循环加进List:
for (int id = 0; id < listView_hisNotice.Items.Count; id++)
{
string value = listView_hisNotice.Items[id].SubItems[index].Text.Trim();
KeyValuePair<string, ListViewItem> tmpkeyvalue = new KeyValuePair<string, ListViewItem>(value, listView_hisNotice.Items[id]);
SortedKeyValuePair.Add(tmpkeyvalue);
}
最后,调用刚才的方法,进行排序:
// 排序
CGlobal.SortKeyValuePairList<string, ListViewItem>.SortKeyValuePair(ref SortedKeyValuePair, bByStringAsc);
这样输出的结果就是排序好的。
PS:
如果是对数值排序,则构造的键值对是int型的:
KeyValuePair<int, ListViewItem> tmpkeyvalue = new KeyValuePair<int, ListViewItem>(value, listView_hisNotice.Items[id]);