C#對集合類進行快速排序
C#對集合類進行快速排序
/// <summary> /// 對集合進行排序,如 /// List<User> users=new List<User>(){.......} /// ListSorter.SortList<list<User>,User>(ref users,"Name",SortDirection.Ascending); /// </summary> public class ListSorter { public static void SortList<TCollection, TItem>(ref TCollection list, string property, SortDirection direction) where TCollection : IList<TItem> { PropertyInfo[] propertyinfos = typeof(TItem).GetProperties(); foreach (PropertyInfo propertyinfo in propertyinfos) { if (propertyinfo.Name == property) //取得指定的排序屬性 { QuickSort<TCollection, TItem>(ref list, 0, list.Count - 1, propertyinfo, direction); } } } /// <summary> /// 快速排序算法 /// </summary> /// <typeparam name="TCollection">集合類型,需要實現Ilist<T>集合</typeparam> /// <typeparam name="TItem">集合中對象的類型</typeparam> /// <param name="list">集合對象</param> /// <param name="left">起始位置,從0開始</param> /// <param name="right">終止位置</param> /// <param name="propertyinfo">集合中對象的屬性,屬性必須要實現IComparable接口</param> /// <param name="direction">排序類型(升序或降序)</param> private static void QuickSort<TCollection, TItem>(ref TCollection list, int left, int right, PropertyInfo propertyinfo, SortDirection direction) where TCollection : IList<TItem> { if (left < right) { int i = left, j = right; TItem key = list[left]; while (i < j) { if (direction == SortDirection.Ascending) { while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[j], null)) < 0) { j--; } if (i < j) { list[i] = list[j]; i++; }while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[i], null)) > 0) { i++; } if (i < j) { list[j] = list[i]; j--; } list[i] = key; } else { while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[j], null)) > 0) { j--; } if (i < j) { list[i] = list[j]; i++; } while (i < j && ((IComparable)propertyinfo.GetValue(key, null)).CompareTo((IComparable)propertyinfo.GetValue(list[i], null)) < 0) { i++; } if (i < j) { list[j] = list[i]; j--; } list[i] = key; } } //執行遞歸調用 QuickSort<TCollection, TItem>(ref list, left, i - 1, propertyinfo, direction); QuickSort<TCollection, TItem>(ref list, i + 1, right, propertyinfo, direction); } }
} /// <summary> /// 排序類型 /// </summary> public enum SortDirection { Ascending, Descending }</pre>
本文由用戶 pb44 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!