這是我的代碼:使用.First()和.Count()打破了IEnumerable?
protected IEnumerable<Hotel> Hotels;
protected Hotel Hotel;
Hotels = from Hotel hotel in new Hotels()
select hotel;
Response.Write("RES " + Hotels.Count() + "<br />");
if (Hotels.Count() > 0)
{
Hotel = Hotels.First();
}
Response.Write("RES " + Hotels.Count() + "<br />");
Response.Write("RES " + Hotels.Count() + "<br />");
好,酒店有它1項。但結果如下:
RES 1
RES 0
RES 1
爲什麼?似乎.First()
與迭代器混淆?我怎樣才能解決它使用IEnumberable? (不使用另一種列表,我需要IEnumerable)。
酒店是如何填充的以及底層存儲空間是什麼它實際上是參考一個列表? –
2012-03-12 09:37:49
行爲取決於酒店究竟是什麼。如果它包含一些可以更改的數據源的引用/連接,那麼顯然這個值可以在對Count的調用之間改變,或者如果使用yield return實現它,它可以做任何事情。嘗試對它調用ToArray(),然後對ToArray()返回的值進行計數等操作,然後知道該集合有固定的快照。 – Foo42 2012-03-12 09:38:53
酒店的實際實施可能會造成問題。例如,它適用於列表。 – Botz3000 2012-03-12 09:39:06