How to get an indexed item of an IEnumerable object (Linq)

If you have an IEnumerable<T> collection of some objects T and you need to get a particular item out of that collection, you cannot use the standard indexing that you would normally use with brackets ([index]).  If you try you will get an error such as:

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

image

But there is the extension method ElementAt(index) (in the System.Linq namespace) for IEnumerable<T> that will allow you to get at that particular indexed item:

MyItem = MyIEnumerableExpression.ElementAt(index);

From the MSDN Documentation: http://msdn.microsoft.com/en-us/library/bb299233.aspx

image



1 Comment

  • What about the opposite. I have IEnumerable and an item, I want to know its index how to know that?
    Shall I use ToArray then use IndexOf, seems a bit overkill?

Comments have been disabled for this content.