C#中如何访问IEnumerable对象中的索引?我有一个IEnumerable对象。我想根据索引访问,例如:for(i=0;i<=Model.Products;i++){???}这可能吗?varmyProducts=Models.Products.ToList();for(i=0;i首先,你确定它真的是IEnumerator而不是IEnumerable吗?我强烈怀疑它实际上是后者。另外,这个问题并不完全清楚。你有索引吗,想在那个指数?如果是这样,如果你有一个IEnumerable(不是IEnumerator),你可以这样做:usingSystem.Linq;...varproduct=Model.Products.ElementAt(i);如果你想枚举整个collection,但是想有每个元素的索引,那么VA或者Nestor的答案就是你想要的,IEnumerator中没有索引。使用foreach(variteminModel.Products){...item...}如果需要,您可以创建自己的索引:inti=0;foreach(Model.Products中的varitem){...item...i++;}foreach(varindexedProductinModel.Products.Select((p,i)=>new{Product=p,Index=i}){......indexedProduct.Product......indexProduct.Index。..//这就是你需要的。...}按索引检索项目的最佳方法是使用Linq以这种方式使用数组引用你的可枚举集合:#AccesstheindexintheIEnumerableobject?Allthe分享的内容,如果对大家有用,需要了解更多C#学习教程,希望大家多多关注---usingSystem.Linq;...classModel{IEnumerableProducts;}...//Somewhere在您的解决方案中,//假设模型是Model类的实例//并且Products引用Product的具体通用集合//例如,List。...varitem=model.Products.ToArray()[索引];本文采集自网络,不代表立场,如涉及侵权,请点击右下角联系管理员删除,转载请注明出处:
