【问题标题】:Sorting a linked list in ascending and decending order按升序和降序对链表进行排序
【发布时间】:2014-08-15 01:00:28
【问题描述】:

我有一个通用链表,目前由整数组成,我想默认按升序对它们进行排序,然后切换一个布尔值以按降序对它们进行排序。我该怎么做呢?

【问题讨论】:

    标签: c# sorting linked-list


    【解决方案1】:

    假设您的链表实现了IEnumerable<T>(它可能应该这样做!),您可以只使用 LINQ 函数OrderByOrderByDescending

    对于整数,默认比较器很好,所以你只需写:

    bool ascending = true;
    var orderedEnumerable = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x);
    

    或者,使用函数和默认参数:

    IOrderedEnumerable<int> GetOrderedNumbers(bool ascending = true)
    {
          return ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x);
    }
    

    OrderBy 的 MSDN:http://msdn.microsoft.com/en-us/library/vstudio/bb534966(v=vs.100).aspx

    【讨论】:

    • 这是一个很好的答案,我个人永远不会想到这个解决方案。尽管链表是可枚举的(根据定义),但我不会在 IEnumerable 接口和链表之间建立(非常明显的)连接。向您致敬,先生!
    • 是否有不使用 IEnumerable 的替代方案?
    • @user3113376 当然,您可以推出自己的排序算法(选择您喜欢的、快速排序、合并排序、堆排序等)。 LINQ 仅适用于IEnumerable,实现它基本上只是实现迭代器模式。它可能值得沿着这条路线走,因为它允许您使用 LINQ、foreach 和延迟枚举。如果您要问的话,我不知道有任何其他“内置”功能可以做到这一点。
    【解决方案2】:

    如果您使用 .NET 的 LinkedList&lt;T&gt;,而后者又实现了 IEnumerable&lt;T&gt;,您可以使用以下一些解决方案:

    这个扩展方法返回一个LinkedList&lt;T&gt;类型的排序副本

    public static LinkedList<TSource> SortedAscending<TSource, TKey>(
        this LinkedList<TSource> source,
        Func<TSource, TKey> keySelector)
    {
        LinkedList<TSource> tempLinkedList = new LinkedList<TSource>();
        IEnumerable<TSource> orderedEnumerable = source.OrderBy(keySelector).AsEnumerable();
        orderedEnumerable.ForEach(value => tempLinkedList.AddLast(value));
        return tempLinkedList;
    }
    

    此扩展方法对LinkedList&lt;T&gt;类型的源进行排序

    public static void SelfSortAscending<TSource, TKey>(
        this LinkedList<TSource> source,
        Func<TSource, TKey> keySelector)
    {
        LinkedList<TSource> tempLinkedList = new LinkedList<TSource>(source);
        source.Clear();
        IEnumerable<TSource> orderedEnumerable = tempLinkedList.OrderBy(keySelector).AsEnumerable();
        orderedEnumerable.ForEach(value => source.AddLast(value));
    }
    

    descending 排序的扩展方法,您可以在以下位置找到: LinkedListHelper (GitHub link)

    顺便说一句,.ForEach() 你可以这样实现:

    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        if (action == null)
            throw new ArgumentNullException(nameof(action));
    
        foreach (T element in source)
            action(element);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2020-11-09
      • 2020-06-06
      • 2018-05-03
      相关资源
      最近更新 更多