Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from List into IEnumerable format

People also ask

How do I change a list to IEnumerable?

We can use the AsEnumerable() function of LINQ to convert a list to an IEnumerable in C#.

How do I make a list IEnumerable?

You can use the extension method AsEnumerable in Assembly System. Core and System. Linq namespace : List<Book> list = new List<Book>(); return list.

How do I add items to an IEnumerable list?

What you can do is use the Add extension method to create a new IEnumerable<T> with the added value. var items = new string[]{"foo"}; var temp = items; items = items. Add("bar");

What is the return type of IEnumerable?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).


You don't need to convert it. List<T> implements the IEnumerable<T> interface so it is already an enumerable.

This means that it is perfectly fine to have the following:

public IEnumerable<Book> GetBooks()
{
    List<Book> books = FetchEmFromSomewhere();    
    return books;
}

as well as:

public void ProcessBooks(IEnumerable<Book> books)
{
    // do something with those books
}

which could be invoked:

List<Book> books = FetchEmFromSomewhere();    
ProcessBooks(books);

You can use the extension method AsEnumerable in Assembly System.Core and System.Linq namespace :

List<Book> list = new List<Book>();
return list.AsEnumerable();

This will, as said on this MSDN link change the type of the List in compile-time. This will give you the benefits also to only enumerate your collection we needed (see MSDN example for this).


Why not use a Single liner ...

IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;

As far as I know List<T> implements IEnumerable<T>. It means that you do not have to convert or cast anything.


IEnumerable<Book> _Book_IE;
List<Book> _Book_List;

If it's the generic variant:

_Book_IE = _Book_List;

If you want to convert to the non-generic one:

IEnumerable ie = (IEnumerable)_Book_List;