简体   繁体   English

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

[英]How does IOrderedEnumerable.ThenBy() in .Net work?

I want to understand how ThenBy works in .Net. 我想了解ThenBy如何在.Net中工作。 (I know how to use it, I just don't understand how Microsoft implemented it!) (我知道如何使用它,我只是不明白微软如何实现它!)

According to the documentation, string_list.OrderBy(Function (x) x.length).ThenBy(Function (x) x) should output a list of strings ordered by length and then alphabetically. 根据文档, string_list.OrderBy(Function (x) x.length).ThenBy(Function (x) x)应输出按长度排序的字符串列表, 然后按字母顺序排列。 How could it possibly work?!? 怎么可能有用?!? The first sort is by length. 第一种是长度。 The second sort should undo the sorting of the first one! 第二种排序应该撤消第一种排序!

Assume this code: 假设这段代码:

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

Here's me trying to implement the last line without using ThenBy : 这是我试图在不使用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

There's some magic going on here... Is there some e.GetPreviousKeySelector() function? 这里有一些神奇的东西......是否有一些e.GetPreviousKeySelector()函数? In fact, I can't even write a function that returns IOrderedEnumerable! 实际上,我甚至无法编写一个返回IOrderedEnumerable的函数!

How could it possibly work?!? 怎么可能有用?!? The first sort is by length. 第一种是长度。 The second sort should undo the sorting of the first one! 第二种排序应该撤消第一种排序!

No, the second sort comparison is only consulted when the primary comparison finds two equal values. 不,只有当主要比较找到两个相等的值时,才会查询第二次排序比较。

The IOrderedEnumerable implementation does this by remembering all the comparisons, effectively - or, as another way of putting it, allowing you to build a comparison from "the current comparison and another one to consult when that returns 0". IOrderedEnumerable实现通过有效地记住所有比较IOrderedEnumerable实现这一点 - 或者,作为另一种方式,允许您从“当前比较和另一个比较,在返回0时进行咨询”构建比较。

I have a blog post series which goes into LINQ to Objects in some depth, providing a complete alternative implementation. 我有一个博客文章系列 ,它深入到LINQ to Objects,提供了一个完整的替代实现。 The basis of IOrderedEnumerable is covered in part 26a and 26b , with more details and optimization in 26c and 26d . IOrderedEnumerable的基础在第26a26b 部分中介绍,在26c26d中有更多细节和优化。

In fact, I can't even write a function that returns IOrderedEnumerable! 实际上,我甚至无法编写一个返回IOrderedEnumerable的函数!

You absolutely can - either by returning the value returned from OrderBy , or by implementing it yourself. 你绝对可以 - 通过返回从OrderBy返回的值,或者自己实现它。

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

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