2013-08-02 62 views
-2

我有一個「exampleClass」,有一個集合「exampleCollection」。 如果exam​​pleClass.ExampleCollection.Count = 0,則exampleClass.ExampleCollection.Select(.... 那麼查詢將產生一個錯誤?選擇計數收集?

我與C#的工作,使用LINQ 謝謝!

+6

您是否試過這樣做? – Matthew

+0

這完全取決於你想要對「Select(...)'的結果做什麼。 – dasblinkenlight

+1

不,它會導致一個空的'IEnumerable ' – Khan

回答

1

如果exampleClass.ExampleCollection.Count() == 0,將exampleClass.ExampleCollection.Select(....)產生錯誤?

不,它只是產生一個空IEnumerable<T>First()Last()會產生錯誤,但不Select()

如果exampleClass.ExampleCollectionnull那麼你得到NullReferenceException

+0

別忘了Single()'。 –

1

不,你只會收到一個空的IEnumerable<T>,更具體一個WhereSelectListIterator<T, bool>

但有趣的是要注意,如果集合爲空,則會拋出錯誤,但在擴展方法Select內。該行爲是不同的,因爲選擇的方法是不是你的集合的實例方法,這是一個擴展方法,如下圖所示:

IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector); 

隨着擴展方法,你的對象傳遞給靜態方法(擴展名)爲一個參數,所以NullRererenceException可能或可能不會被拋出(取決於內部實現)。在選擇方法的情況下,