Does list.count physically iterate through the list to count it, or does it keep a pointer

后端 未结 5 1933
臣服心动
臣服心动 2021-01-11 12:55

I am stepping through a large list of object to do some stuff regarding said objects in the list.

During my iteration, I will remove some objects from the list depen

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 13:50

    List is implemented as an array list, and it keeps track of its own size, so invoking the .Count property doesn't require any iteration.

    If you call the LINQ .Count() extension method, this will check whether the underlying IEnumerable<> implements ICollection (which a List<> does), and use the .Count property on that interface if possible. So this won't cause any iteration to occur either.

    Incidentally, there are other problems you're going to encounter if you attempt to remove items from your list while iterating through it. It's not really clear how iteration should behave when you are removing elements out from under the iterator, so List<>s will avoid this issue entirely by throwing an exception if the list has been modified since its enumerator was created.

提交回复
热议问题