List<string> list = new List<string>() {"a", "b", "c"};
IEnumerable<string> enumerable = list;
int c1 = list.Count;
int c2 = list.Count();
int c3 = enumerable.Count();
之間是否存在差異?這些最後3條語句在性能和實現方面是否存在差異?將list.Count()
表現更差或與list.Count
相同,並且如果參考的類型爲IEnumerable<string>
,那麼這很重要嗎?Count()(linq擴展名)和List <T>。Count
如果IEnumerable是ICollection(如List),因此具有.Count屬性,那麼當您使用.Count()方法時,Linq會將其用作快捷方式。這意味着無論你使用什麼都不重要。 – Dolbz
這是錯誤的。 Count()被編碼爲它只循環計算,如果你調用Count()的元素沒有實現ICollection本身。 –