我寫了這個:爲什麼不能使用迭代器塊與IOrderedEnumerable
using System;using System.Linq;
static class MyExtensions
{
public static IEnumerable<T> Inspect<T> (this IEnumerable<T> source)
{
Console.WriteLine ("In Inspect");
//return source; //Works, but does nothing
foreach(T item in source){
Console.WriteLine(item);
yield return item;
}
}
}
然後去與這個來測試它:
var collection = Enumerable.Range(-5, 11)
.Select(x => new { Original = x, Square = x * x })
.Inspect()
.OrderBy(x => x.Square)
//.Inspect()
.ThenBy(x => x.Original)
;
foreach (var element in collection)
{
Console.WriteLine(element);
}
第一次使用的Inspect()
工作正常。第二個評論說,不會編譯。 OrderBy
的回報爲IOrderedEnumerable
。我還以爲IOrderedEnumerable
是,一個IEnumerable
但是,與拳滾,我想:
public static IOrderedEnumerable<T> Inspect<T> (this IOrderedEnumerable<T> source)
{
Console.WriteLine ("In Inspect (ordered)");
foreach(T item in source){
Console.WriteLine(item);
yield return item;
}
}
但這不會編譯任。我被告知我不能有一個迭代器塊,因爲System.Linq.IOrderedEnumberable不是一個迭代器接口類型。
我錯過了什麼?我不明白爲什麼人們不希望按照與原始集合相同的方式迭代有序集合。
(使用單聲道2.10.8.1,這有效地C#是4.0,和MonoDevelop的2.8.6.3)
UPDATE:
作爲joshgo麻煩指出的,我可以採取的IOrderedEnumerable
輸入參數,它的確行事as-aIEnumerable
。但爲了迭代,我必須返回IEnumerable
,並且我的原始錯誤是由ThenBy
引起的,它堅持給出IOrderedEnumerable
。非常合理。但有沒有辦法在這裏滿足ThenBy
?
UPDATE2:有沒有意義的,因爲:
在兩個答案的代碼打(這兩者都是非常有幫助),我終於明白了爲什麼我不能用產量與IOrderedEnumerable回來後這些值必須完全可用才能進行排序。因此,不用一個帶有yield的循環,我最好使用一個循環來打印所有項目,然後在最後一次返回源代碼。
這完全不回答這個問題:/ – Earlz
@Earlz不會! (啊,我看你在joshgo做了一個重大的編輯之前寫了你的評論。) –
啊哈!你是對的,問題在於對ThenBy()的調用。實際上'IEnumerable檢查(這個IEnumerable 源)''OrderBy()'沒有問題。但重寫不能僅僅通過返回類型來改變;我想知道是否有辦法滿足ThenBy? –