簡體   English   中英

按升序和降序對鏈接列表進行排序

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

我有一個通用的鏈表,當前由整數組成,我想默認情況下按升序對它們進行排序,然后切換一個布爾值以按降序對它們進行排序。 我將如何去做呢?

假設您的鏈表實現了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);
}

用於訂購的MSDN: http : //msdn.microsoft.com/zh-cn/library/vstudio/bb534966 (v=vs.100) .aspx

如果使用.NET的LinkedList<T>來實現IEnumerable<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;
}

此擴展方法對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));
}

您可以在以下位置找到降序擴展方法: LinkedListHelper(GitHub鏈接)

順便說一下, .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