我想了解 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 的函数!
最佳答案
How could it possibly work?!? The first sort is by length. The second sort should undo the sorting of the first one!
不,仅当主要比较发现两个相等的值时才查阅第二次排序比较。
IOrderedEnumerable
实现通过有效地记住所有比较来做到这一点 - 或者,作为另一种方式,允许您从“当前比较和另一个在返回 0 时引用的比较”构建比较。我有一个 blog post series,它深入研究了 LINQ to Objects,提供了一个完整的替代实现。
IOrderedEnumerable
的基础包含在 part 26a 和 26b 中,更多细节和优化在 26c 和 26d 中。In fact, I can't even write a function that returns IOrderedEnumerable!
您绝对可以 - 通过返回从
OrderBy
返回的值,或者自己实现它。
关于.net - .Net 中的 IOrderedEnumerable.ThenBy() 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10827899/