如何在C#中访问IEnumerable对象中的索引?

时间:2009-10-31 12:13:50

标签: c# ienumerable

我有一个IEnumerable对象。我想基于索引访问例如:

for(i=0; i<=Model.Products; i++)
{
      ???
}

这可能吗?

5 个答案:

答案 0 :(得分:103)

首先,您确定它真的是IEnumerator而不是IEnumerable吗?我强烈怀疑它实际上是后者。

此外,问题并不完全清楚。你有一个索引,并且你想在该索引处获得一个对象吗?如果是这样,如果确实你有IEnumerable(不是IEnumerator),你可以这样做:

using System.Linq;
...
var product = Model.Products.ElementAt(i);

如果你想枚举整个集合,但又希望每个元素都有一个索引,那么V.A.或者Nestor的答案就是你想要的。

答案 1 :(得分:26)

IEnumerator中没有索引。使用

foreach(var item in Model.Products)
{
   ...item...
}

如果您愿意,可以制作自己的索引:

int i=0;
foreach(var item in Model.Products)
{
    ... item...
    i++;
}

答案 2 :(得分:21)

var myProducts = Models.Products.ToList();
for(i=0; i< myProducts.Count ; i++)
{
      //myProducts[i];
}

答案 3 :(得分:8)

foreach(var indexedProduct in Model.Products.Select((p, i)=> new {Product = p, Index = i})
{
   ...
   ...indexedProduct.Product...
   ...indexProduct.Index ...//this is what you need.
   ...
}

答案 4 :(得分:0)

通过索引检索项目的最佳方法是使用Linq以这种方式使用数组引用您的可枚举集合:

using System.Linq;
...
class Model {
    IEnumerable<Product> Products;
}
...
// Somewhere else in your solution,
// assume model is an instance of the Model class
// and that Products references a concrete generic collection
// of Product such as, for example, a List<Product>.
...
var item = model.Products.ToArray()[index];