我正在通过这里的 101 个 Linq 教程进行编码:
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
大多数例子都很简单,但这个例子让我陷入了循环:
[Category("Ordering Operators")]
[Description("The first query in this sample uses method syntax to call OrderBy and ThenBy with a custom comparer to " +
"sort first by word length and then by a case-insensitive sort of the words in an array. " +
"The second two queries show another way to perform the same task.")]
public void Linq36()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry", "b1" };
var sortedWords =
words.OrderBy(a => a.Length)
.ThenBy(a => a, new CaseInsensitiveComparer());
// Another way. TODO is this use of ThenBy correct? It seems to work on this sample array.
var sortedWords2 =
from word in words
orderby word.Length
select word;
var sortedWords3 = sortedWords2.ThenBy(a => a, new CaseInsensitiveComparer());
Run Code Online (Sandbox Code Playgroud)
无论我使用哪种单词组合,长度始终是第一个排序标准……即使我不知道第二个语句(没有 orderby!)如何知道原始 orderby 子句是什么。
我要疯了吗?谁能解释一下 Linq 如何“记住”最初的顺序是什么?
的返回类型OrderBy不是IEnumerable<T>。它是IOrderedEnumerable<T>。这是一个“记住”给定的所有排序的对象,只要您不调用另一个将变量变回 的方法,IEnumerable它就会保留该知识。
有关详细信息,请参阅 Jon Skeets 精彩的博客系列 Eduling,其中他重新实现了 Linq-to-objects。OrderBy/ThenBy上的关键条目是: