I'm trying to do something with every feature in featureclass using "foreach" :

ILayer layer = map.Layer[0];
IFeatureClass fclayer = (layer as IFeatureLayer2).FeatureClass;

   foreach (IFeature feature in fclayer)
      {//do something with feature }

but error appears: foreach statement cannot operate on variables of type 'ESRI.ArcGIS.Geodatabase.IFeatureClass' because 'ESRI.ArcGIS.Geodatabase.IFeatureClass' does not contain a public definition for 'GetEnumerator'.

How to organize a enumeration in FC?

Using: C#, ArcGIS 10.2.2

  • 1
    What object type is fclayerSTR? – Barbarossa Sep 13 '17 at 17:51
  • Sorry, I fixed that mistake in code – Alex Sep 13 '17 at 18:12

Foreach does not work because IFeatureClass does not implement IEnumerable.

You need to use a cursor to loop through features.

To simply loop through all features just do something like this:

//filter is an IQueryFilter, this can also just be null
//the boolean is true if you want to use recycling (1 feature in memory at a time)
IFeatureCursor search = featureClass.Search(filter, true);
IFeature sourceFeature;
while ((sourceFeature = search.NextFeature()) != null)
    //do stuff here
//cursors need to be released when you are finished

I would suggest reading more about cursors here. (it's from an older version, but not much has changed)

  • Thanks for answer, but using cursor and "while" loop is too slowly for me. For example, "for" loop(without using cursor) is about 100 times more slowly then "while" loop(using cursor); "while" is good but not enouth. There was an old GIS soft "ArcView" ; scripts in avenu language worked much more faster then my Add-ins (made in Visual Studio in С#). So I'm trying to find the most fast iterating method to operate with every feature in FC. May be I should start a new question for this... – Alex Sep 13 '17 at 19:57
  • 1
    I find the cursor to work at an acceptable speed most of the time. It could be a hardware or network issue. Also make sure that ALL arcobjects are created in the same thread. If they are not then the application will become extremely slow. This shouldn't be an issue if you are running everything on the main thread. – danielm Sep 14 '17 at 16:49
  • Can you halp me in this question? Which way is most fast to iterate features? – Alex Sep 14 '17 at 18:33

You can't just iterate features in a feature class. You have to perform a query and obtain a cursor. Then you can iterate the features in the cursor.

Look up IQueryFilter, IFeatureCursor, and IFeatureClass.Search

You should find what you need there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.