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



Published 29 January 2010 04:32 AM by Jeff Widmer

Comments

# Twitter Trackbacks for How to get an indexed item of an IEnumerable object (Linq) - Jeff Widmer's Blog [asp.net] on Topsy.com said on 31 January, 2010 02:26 AM

Pingback from  Twitter Trackbacks for                 How to get an indexed item of an IEnumerable object (Linq) - Jeff Widmer's Blog         [asp.net]        on Topsy.com

# How to get an indexed item of an IEnumerable object (Linq) | 007Nova Articles said on 07 February, 2010 09:10 AM

Pingback from  How to get an indexed item of an IEnumerable object (Linq) | 007Nova Articles

# Shehab said on 11 March, 2010 08:35 AM

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?

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

Go

This Blog

News

Syndication