开发者

When to expect IEnumerable and when to expect IQueryable from a Linq query

I am having some trouble understanding when Linq is giving me an IQueryable result and when it is giving me an IEnumerable result.

Example:

I am using EF and I have two entities Location and Configuration. Each Location can have multiple Configurations.

The following query is giving me an IQueryable as result:

Context.Locations.Where(l => l.Name == "SomeName")

whereas t开发者_开发技巧he following is giving me an IEnumerable as result:

Context.Locations.Where(l => l.Name == "SomeName").First().Configurations.Select(c => c)

Why is that?


In general, LINQ extension methods on IQueryable (defined in Queryable) return IQueryables, and the ones on IEnumerable (defined in Enumerable) return IEnumerables. In this particular case, Configurations is a collection (IEnumerable) on the first returned Location object. Therefore the .Select call returns an IEnumerable.

EDIT: To make it all execute remotely, you could try this:

Context.Locations.Where(l => l.Name == "SomeName").Configurations

Assuming that your filter on Locations is only going to return one row, you should get the same result. Of course it will be an IQueryable, but that shouldn't make a difference. If you need to materialize it, you can do something like:

Context.Locations.Where(l => l.Name == "SomeName").Configurations.ToList()


Basically, IQueryable allows for remote data sources (like SQL Server). It will work against the database, if possible. IEnumerable works with in-memory collections.

So, if you are querying a SQL Server database, you will get an IQueryable. Otherwise it'll be an IEnumerable.

This article may further help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜