Search code examples
c#ienumerable

How to get item from IEnumerable collection using its index in C#?


I have IEnumerable list of customerList and index. Now I want to get item of IEnumerable based on index.

For example, if index = 3, it should provide me 3rd item of the IEnumerable .

Please guide.

IEnumerable<Customer> customerList = new Customer[] 
{ 
     new Customer { Name = "test1", Id = 999 }, 
     new Customer { Name = "test2", Id = 915 }, 
     new Customer { Name = "test8", Id = 986 },
     new Customer { Name = "test9", Id = 988 },
     new Customer { Name = "test4", Id = 997 },
     new Customer { Name = "test5", Id = 920 },
};

int currentIndex = 3;   //want to get object Name = "test8", Id = 986

Solution

  • For example, if index = 3, it should provide me 3rd item of the IEnumerable

    You know that indexes are zero based in .NET? However, you can use ElementAt:

    Customer c = customerList.ElementAt(currentIndex); // 4th
    

    Use ElementAtOrDefault to prevent an exception if there are not enough items, then you get null:

    Customer c = customerList.ElementAtOrDefault(currentIndex); // 4th or null
    

    These methods are optimized in a way that they use the IList<T> indexer. So in your example there is actually an Customer[] which implements that interface, hence it will use the indexer.

    If the sequence does not implement IList<T> it will be enumerated to find the item at this index.