How to access index in IEnumerable object in C#?

后端 未结 5 1547
-上瘾入骨i
-上瘾入骨i 2020-12-18 18:12

I have an IEnumerable object. I would like to access based on index for instance:

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

Is this

相关标签:
5条回答
  • 2020-12-18 18:50
    var myProducts = Models.Products.ToList();
    for(i=0; i< myProducts.Count ; i++)
    {
          //myProducts[i];
    }
    
    0 讨论(0)
  • 2020-12-18 18:57
    foreach(var indexedProduct in Model.Products.Select((p, i)=> new {Product = p, Index = i})
    {
       ...
       ...indexedProduct.Product...
       ...indexProduct.Index ...//this is what you need.
       ...
    }
    
    0 讨论(0)
  • 2020-12-18 19:01

    There is no index in IEnumerator. Use

    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++;
    }
    
    0 讨论(0)
  • 2020-12-18 19:01

    The best way to retrieve an item by index is to reference your enumerable collection with an array using Linq in this way:

    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];
    
    0 讨论(0)
  • 2020-12-18 19:05

    First of all, are you sure it's really IEnumerator and not IEnumerable? I strongly suspect it's actually the latter.

    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:

    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.

    0 讨论(0)
提交回复
热议问题