如何在 C# 中访问 IEnumerable 对象中的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1654209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access index in IEnumerable object in C#?
提问by dcpartners
I have an IEnumerable object. I would like to access based on index for instance:
我有一个 IEnumerable 对象。例如,我想基于索引访问:
for(i=0; i<=Model.Products; i++)
{
???
}
Is this possible?
这可能吗?
采纳答案by Graviton
var myProducts = Models.Products.ToList();
for(i=0; i< myProducts.Count ; i++)
{
//myProducts[i];
}
回答by Nestor
There is no index in IEnumerator. Use
IEnumerator 中没有索引。用
foreach(var item in Model.Products)
{
...item...
}
you can make your own index if you want:
如果需要,您可以创建自己的索引:
int i=0;
foreach(var item in Model.Products)
{
... item...
i++;
}
回答by V.A.
foreach(var indexedProduct in Model.Products.Select((p, i)=> new {Product = p, Index = i})
{
...
...indexedProduct.Product...
...indexProduct.Index ...//this is what you need.
...
}
回答by Pavel Minaev
First of all, are you sure it's really IEnumerator
and not IEnumerable
? I strongly suspect it's actually the latter.
首先,你确定是真的IEnumerator
还是不是IEnumerable
?我强烈怀疑它实际上是后者。
Furthermore, the question is not entirely clear. Do you have an index, and you want to get an object at that index? If so, and if indeed you have an IEnumerable
(not IEnumerator
), you can do this:
此外,这个问题并不完全清楚。您是否有索引,并且想要在该索引处获取一个对象?如果是这样,如果你确实有一个IEnumerable
(not IEnumerator
),你可以这样做:
using System.Linq;
...
var product = Model.Products.ElementAt(i);
If you want to enumerate the entire collection, but also want to have an index for each element, then V.A.'s or Nestor's answers are what you want.
如果您想枚举整个集合,但还想为每个元素设置一个索引,那么 VA 或 Nestor 的答案就是您想要的。
回答by bert
The best way to retrieve an item by index is to reference your enumerable collection with an array using Linq in this way:
按索引检索项目的最佳方法是通过以下方式使用 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];