C# Collection使用Linq排序的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gao271003105/article/details/81532703
  public static void Sort<TSource, TKey>(Collection<TSource> source, Func<TSource, TKey> keySelector)
        {
            List<TSource> sortedList = source.OrderBy(keySelector).ToList();
            source.Clear();
            foreach (var sortedItem in sortedList)
                source.Add(sortedItem);
        }

        public static void SortDescending<TSource, TKey>(Collection<TSource> source, Func<TSource, TKey> keySelector)
        {
            List<TSource> sortedList = source.OrderByDescending(keySelector).ToList();
            source.Clear();
            foreach (var sortedItem in sortedList)
                source.Add(sortedItem);
        }

        public static void Sort<T>(ObservableCollection<T> collection) where T : IComparable
        {
            List<T> sortedList = collection.OrderBy(x => x).ToList();
            for (int i = 0; i < sortedList.Count(); i++)
            {
                collection.Move(collection.IndexOf(sortedList[i]), i);
            }
        }

ToList会生成新的对象,所以需要重新添加一下。

如果还想要使用原来的对象,则可以在原来的数据类型上实现GetHashCode和Equal,然后用source[source.IndexOf(List[i])]这样去重新添加原来的引用

猜你喜欢

转载自blog.csdn.net/gao271003105/article/details/81532703