Returning IEnumerable vs. IQueryable

前端 未结 14 2492
梦毁少年i
梦毁少年i 2020-11-21 22:59

What is the difference between returning IQueryable vs. IEnumerable, when should one be preferred over the other?



        
14条回答
  •  执念已碎
    2020-11-21 23:57

    In addition to first 2 really good answers (by driis & by Jacob) :

    IEnumerable interface is in the System.Collections namespace.

    The IEnumerable object represents a set of data in memory and can move on this data only forward. The query represented by the IEnumerable object is executed immediately and completely, so the application receives data quickly.

    When the query is executed, IEnumerable loads all the data, and if we need to filter it, the filtering itself is done on the client side.

    IQueryable interface is located in the System.Linq namespace.

    The IQueryable object provides remote access to the database and allows you to navigate through the data either in a direct order from beginning to end, or in the reverse order. In the process of creating a query, the returned object is IQueryable, the query is optimized. As a result, less memory is consumed during its execution, less network bandwidth, but at the same time it can be processed slightly more slowly than a query that returns an IEnumerable object.

    What to choose?

    If you need the entire set of returned data, then it's better to use IEnumerable, which provides the maximum speed.

    If you DO NOT need the entire set of returned data, but only some filtered data, then it's better to use IQueryable.

提交回复
热议问题