最近在寫一個功能是,在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]);