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

如何在C#中访问IEnumerable对象中的索引?,c#,ienumerable,C#,Ienumerable,我有一个IEnumerable对象。我想基于索引访问,例如: for(i=0; i<=Model.Products; i++) { ??? } for(i=0;ivar myProducts=Models.Products.ToList(); 对于(i=0;i

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

for(i=0; i<=Model.Products; i++)
{
      ???
}
for(i=0;i
var myProducts=Models.Products.ToList();
对于(i=0;i
IEnumerator中没有索引。请使用

foreach(var item in Model.Products)
{
   ...item...
}
如果需要,您可以创建自己的索引:

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

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

此外,问题还不完全清楚。您是否有索引,并且希望在该索引处获取对象?如果有,并且如果确实有
IEnumerable
(不是
IEnumerator
),您可以执行以下操作:

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

如果您想枚举整个集合,但又想为每个元素建立索引,那么V.A.或Nestor的答案就是您想要的。

按索引检索项的最佳方法是使用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];
使用System.Linq;
...
类模型{
可数产品;
}
...
//在你的解决方案中的其他地方,
//假设模型是模型类的一个实例
//产品引用了一个具体的通用集合
//指产品,例如列表。
...
var item=model.Products.ToArray()[index];

还有一个beaware.ToList()正在内存中创建一个新列表。这值得吗(仅仅为了索引而浪费了这么多?)这太糟糕了。所以,如果有10000个产品,他需要第5个,你告诉他先将所有10k加载到内存中,然后丢弃他不需要的9554?@Nestor:那真的要视情况而定。我看不出需要索引的理由(计数器就可以了),所以谁知道呢。@Avram An
IEnumerator
要获取的项的索引是完全明智的。@Servy IEnumerator与IEnumerable搭配,需要将IEnumerable添加为question@Avram不,你不需要问。他可以问任何他想问的问题。他选择问关于
IEnumerator
,这是一个非常好的问题。仅仅因为它不是您想要回答/已经回答的问题,并不意味着您应该更改此问题。令人尴尬的是,这不是公认的答案。我在尝试编写一个函数时遇到了一个问题,该函数需要获取列表或数组(“没问题!我只使用IEnumerable!”)-结果发现索引不起作用。ElementAt是完美的解决方案…不枚举整个结构。(我可以想象有人在循环中使用枚举解决方案来访问每个插槽…啊…)
using System.Linq;
...
var product = Model.Products.ElementAt(i);
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];