One benefit of a set is that it can be traversed through foreach. programming code in this way looks more elegant than using the for method (my opinion ).
However, if you want to use foreach traversal to delete the elements in the Set, an error occurs. After querying the information, we can know that the set can implement foreach traversal because it implements the system. Collections. ienumerable interface. Ienumerable only defines one method:
1 interface ienumerable
2 {
3 ienumerator getenumerator ();
4}
Getenumerator () is used to return enumeration objects. It can be seen that the enumeration object implementation interface system. Collections. ienumerator. The ienumerator interface is defined: 1 interface ienumerator
2 {
3 object current {Get ;}
4 bool movenext ();
5 void reset ();
6}
We can clearly see that the enumeration attribute only has get but no set. Therefore, it is not sufficient to perform any modification operations on the enumerated elements.
The above is my personal understanding. If something is wrong, please give me more advice!
The following describes how to delete a set (consciously stupid, but effective ): 1 For (INT I = items. Count-1; I>-1; I = items. Count-1)
2 {
3 items. Remove (I );
4}
Is the speed fast?
Put it the safest, and the fastest :) 1 For (INT I = intems. Count-1; I>-1; I --)
2 {
3 items. Remove (I );
4}
In this way, the deletion will fail.