I have a List and I need an IEnumerable, however List.GetEnumerator() returns List.Enumerator ...
Is there a simple way of getting (casting to?) an IEnumerator? (currently I have solved this with a loop, however I feel casting the enumerator would be a far better solution)...
IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.
Use the ToList() Method to Convert an IEnumerable to a List in C# Copy Enumerable.
IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.
A List<T>
is already an IEnumerable<T>
.
I think you will find that a generic List implements IEnumerable, so you don't need to do anything.
What situation are you trying to use this in?
List<T>
implements IEnumerable<T>
, so you don't need to cast it:
public IEnumerable<T> GetIEnumerable()
{
List<T> yourListOfT = GetList();
return yourListOfT;
}
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