如果不計算struct
元素的IEnumerables<T>
集合中的所有元素,檢測元素是否爲空的最佳方法是什麼?如何知道IEnumerable <ValueType>是否爲空,而不計算所有?
例如,在class
元件我將通常與測試第一或默認:
myEnumerableReferenceTypeElements.FirstOrDefault() == null
因爲null是通常不被迭代中集合的有效值。
但是,對於所有值必須位於預定範圍內的值類型的情況下,默認值(例如int默認值爲0)也是集合中的一個可行項目。
myValueTypeInt32Elements.FirstOrDefault() == 0 // can't tell if empty for sure
無論基礎類型如何,您都應該使用'Any'。 – jason 2011-03-14 16:24:39
[C#:推薦的方法檢查序列是否爲空]的可能重複(http://stackoverflow.com/questions/2094729/c-recommended-way-to-check-if-a-sequence-is-empty) – nawfal 2013-02-18 20:54:47