Convert from List into IEnumerable format

◇◆丶佛笑我妖孽 提交于 2019-12-17 17:36:35

问题


IEnumerable<Book> _Book_IE
List<Book> _Book_List

How shall I do in order to convert _Book_List into IEnumerable format?


回答1:


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



回答2:


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




回答3:


Why not use a Single liner ...

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



回答4:


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




回答5:


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;



回答6:


You need to

using System.Linq;

to use IEnumerable options at your List.



来源:https://stackoverflow.com/questions/4700613/convert-from-list-into-ienumerable-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!