我有一個「exampleClass」,有一個集合「exampleCollection」。 如果exampleClass.ExampleCollection.Count = 0,則exampleClass.ExampleCollection.Select(.... 那麼查詢將產生一個錯誤?選擇計數收集?
我與C#的工作,使用LINQ 謝謝!
我有一個「exampleClass」,有一個集合「exampleCollection」。 如果exampleClass.ExampleCollection.Count = 0,則exampleClass.ExampleCollection.Select(.... 那麼查詢將產生一個錯誤?選擇計數收集?
我與C#的工作,使用LINQ 謝謝!
如果
exampleClass.ExampleCollection.Count() == 0
,將exampleClass.ExampleCollection.Select(....)
產生錯誤?
不,它只是產生一個空IEnumerable<T>
。First()
和Last()
會產生錯誤,但不Select()
。
如果exampleClass.ExampleCollection
是null
那麼你將得到NullReferenceException
。
別忘了Single()'。 –
不,你只會收到一個空的IEnumerable<T>
,更具體一個WhereSelectListIterator<T, bool>
。
但有趣的是要注意,如果集合爲空,則會拋出錯誤,但在擴展方法Select
內。該行爲是不同的,因爲選擇的方法是不是你的集合的實例方法,這是一個擴展方法,如下圖所示:
IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
隨着擴展方法,你的對象傳遞給靜態方法(擴展名)爲一個參數,所以NullRererenceException可能或可能不會被拋出(取決於內部實現)。在選擇方法的情況下,
您是否試過這樣做? – Matthew
這完全取決於你想要對「Select(...)'的結果做什麼。 – dasblinkenlight
不,它會導致一個空的'IEnumerable' –
Khan