Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

ienumerable

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
like image 981
Nanji Mange Avatar asked Nov 02 '18 14:11

Nanji Mange


People also ask

How do I get an item from IEnumerable?

We can get first item values from IEnumerable list by using First() property or loop through the list to get respective element. IEnumerable list is a base for all collections and its having ability to loop through the collection by using current property, MoveNext and Reset methods in c#, vb.net.

What inherits from IEnumerable?

ICollection inherits from IEnumerable. You therefore have all members from the IEnumerable interface implemented in all classes that implement the ICollection interface.

How do I know if IEnumerable has an item?

IEnumerable. Any() will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.

Is IEnumerable a collection?

IEnumerable<T> is an interface that represents a sequence. Now; collections can usually be used as sequences (so... List<T> implements IEnumerable<T> ), but the reverse is not necessarily true. In fact, it isn't strictly required that you can even iterate a sequence ( IEnumerable<T> ) more than once.


1 Answers

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.

like image 57
Tim Schmelter Avatar answered Oct 05 '22 13:10

Tim Schmelter