Returning IEnumerable vs. IQueryable

前端 未结 14 2505
梦毁少年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:38

    In general you want to preserve the original static type of the query until it matters.

    For this reason, you can define your variable as 'var' instead of either IQueryable<> or IEnumerable<> and you will know that you are not changing the type.

    If you start out with an IQueryable<>, you typically want to keep it as an IQueryable<> until there is some compelling reason to change it. The reason for this is that you want to give the query processor as much information as possible. For example, if you're only going to use 10 results (you've called Take(10)) then you want SQL Server to know about that so that it can optimize its query plans and send you only the data you'll use.

    A compelling reason to change the type from IQueryable<> to IEnumerable<> might be that you are calling some extension function that the implementation of IQueryable<> in your particular object either cannot handle or handles inefficiently. In that case, you might wish to convert the type to IEnumerable<> (by assigning to a variable of type IEnumerable<> or by using the AsEnumerable extension method for example) so that the extension functions you call end up being the ones in the Enumerable class instead of the Queryable class.

提交回复
热议问题