简体   繁体   English

按升序和降序对链接列表进行排序

[英]Sorting a linked list in ascending and decending order

I have a generic linked list, currently made up of ints, and I want to sort them by ascending order by default, and then switch a boolean to sort them by descending values. 我有一个通用的链表,当前由整数组成,我想默认情况下按升序对它们进行排序,然后切换一个布尔值以按降序对它们进行排序。 How would I go about doing this? 我将如何去做呢?

Assuming your linked list implements IEnumerable<T> (which it probably should!), you can just use the LINQ functions OrderBy and OrderByDescending . 假设您的链表实现了IEnumerable<T> (可能应该这样做!),则可以只使用LINQ函数OrderByOrderByDescending

For ints, the default comparer is fine, so you would just write: 对于整数,默认比较器就可以了,因此您只需编写:

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

Or, with a function and default args: 或者,使用一个函数和默认参数:

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

MSDN for OrderBy: http://msdn.microsoft.com/en-us/library/vstudio/bb534966(v=vs.100).aspx 用于订购的MSDN: http : //msdn.microsoft.com/zh-cn/library/vstudio/bb534966 (v=vs.100) .aspx

If you use the .NET's LinkedList<T> that, in its turn, implements IEnumerable<T> you can use some of these solutions: 如果使用.NET的LinkedList<T>来实现IEnumerable<T> ,则可以使用以下一些解决方案:

This extension method returns a sorted copy of type LinkedList<T> 此扩展方法返回LinkedList<T>类型的排序副本

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;
}

This extension method sorts the source of type LinkedList<T> 此扩展方法对LinkedList<T>类型的源进行排序

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));
}

Extension methods for descending ordering you can find at: LinkedListHelper (GitHub link) 您可以在以下位置找到降序扩展方法: LinkedListHelper(GitHub链接)

By the way, .ForEach() you could implement like this: 顺便说一下, .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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM