Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get IEnumerable<T> from List<T>?

Tags:

c#

generics

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)...

like image 525
David Božjak Avatar asked Aug 23 '10 12:08

David Božjak


People also ask

What's the difference between IEnumerable T and List t?

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.

Can you cast IEnumerable to List?

Use the ToList() Method to Convert an IEnumerable to a List in C# Copy Enumerable.

What is IEnumerable T?

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>.


3 Answers

A List<T> is already an IEnumerable<T>.

like image 126
leppie Avatar answered Oct 21 '22 03:10

leppie


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?

like image 29
Giles Smith Avatar answered Oct 21 '22 05:10

Giles Smith


List<T> implements IEnumerable<T>, so you don't need to cast it:

public IEnumerable<T> GetIEnumerable()
{
    List<T> yourListOfT = GetList();
    return yourListOfT;
}
like image 38
djdd87 Avatar answered Oct 21 '22 05:10

djdd87