【发布时间】:2014-08-15 01:00:28
【问题描述】:
我有一个通用链表,目前由整数组成,我想默认按升序对它们进行排序,然后切换一个布尔值以按降序对它们进行排序。我该怎么做呢?
【问题讨论】:
标签: c# sorting linked-list
我有一个通用链表,目前由整数组成,我想默认按升序对它们进行排序,然后切换一个布尔值以按降序对它们进行排序。我该怎么做呢?
【问题讨论】:
标签: c# sorting linked-list
假设您的链表实现了IEnumerable<T>(它可能应该这样做!),您可以只使用 LINQ 函数OrderBy 和OrderByDescending。
对于整数,默认比较器很好,所以你只需写:
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,实现它基本上只是实现迭代器模式。它可能值得沿着这条路线走,因为它允许您使用 LINQ、foreach 和延迟枚举。如果您要问的话,我不知道有任何其他“内置”功能可以做到这一点。
如果您使用 .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));
}
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);
}
【讨论】: