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
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.
ICollection inherits from IEnumerable. You therefore have all members from the IEnumerable interface implemented in all classes that implement the ICollection interface.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With