.Net中的IOrderedEnumerable.ThenBy()如何工作?

问题描述 投票:12回答:1

我想了解ThenBy如何在.Net中工作。 (我知道如何使用它,我只是不明白微软如何实现它!)

根据文档,string_list.OrderBy(Function (x) x.length).ThenBy(Function (x) x)应输出按长度排序的字符串列表,然后按字母顺序输出。怎么可能有用?!?第一种是长度。第二种排序应该撤消第一种排序!

假设这段代码:

Dim sorted_by_length As IOrderedEnumerable(Of String)
sorted_by_length = string_list.OrderBy(Function (x) x.length)
sorted_by_length = sorted_by_length.ThenBy(Function

这是我试图在不使用ThenBy的情况下实现最后一行:

Dim sorted_by_length As IOrderedEnumerable(Of String)
sorted_by_length = string_list.OrderBy(Function (x) x.length)
'my implementation of OrderBy:
Dim e as IEnumerator(Of String) = sorted_by_length.GetEnumerator
Do While e.MoveNext
    'I have no idea what to write here!
Loop

这里有一些神奇的东西......是否有一些e.GetPreviousKeySelector()函数?实际上,我甚至无法编写一个返回IOrderedEnumerable的函数!

.net vb.net ienumerable iorderedenumerable
1个回答
13
投票

怎么可能有用?!?第一种是长度。第二种排序应该撤消第一种排序!

不,只有当主要比较找到两个相等的值时,才会查询第二次排序比较。

IOrderedEnumerable实现通过有效地记住所有比较来实现这一点 - 或者,作为另一种方式,允许您构建从“当前比较和另一个比较,当返回0时进行咨询”的比较。

我有一个blog post series深入LINQ to Objects,提供了一个完整的替代实现。 IOrderedEnumerablepart 26a涵盖了26b的基础,在26c26d中有更多细节和优化。

实际上,我甚至无法编写一个返回IOrderedEnumerable的函数!

你绝对可以 - 通过返回从OrderBy返回的值,或者自己实现它。

© www.soinside.com 2019 - 2024. All rights reserved.