How to access index in IEnumerable object in C#?

后端 未结 5 1548
-上瘾入骨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 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 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.
    ...
    var item = model.Products.ToArray()[index];
    

提交回复
热议问题