Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

后端 未结 7 1131
长情又很酷
长情又很酷 2020-12-14 05:41

Is there any specific reason why indexing is not allowed in IEnumerable.

I found a workaround for the problem I had, but just curious to know why it does not allow i

7条回答
  •  一向
    一向 (楼主)
    2020-12-14 05:50

    The IEnumerable interface does not include an indexer, you're probably confusing it with IList

    If the object really is an IList (e.g. List or an array T[]), try making the reference to it of type IList too.

    Otherwise, you can use myEnumerable.ElementAt(index) which uses the Enumerable.ElementAt extension method. This should work for all IEnumerables . Note that unless the (run-time) object implements IList, this will cause all of the first index + 1 items to be enumerated, with all but the last being discarded.

    EDIT: As an explanation, IEnumerable is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable must support all these cases, indexers are excluded from its definition.

提交回复
热议问题