Luis Valencia
Luis Valencia

Reputation: 34008

IEnumerable and IQueryable, which one does it use when I use the var keyword?

I have read about IEnumerable and IQueryable, I have read that IQueryable is better with linq because when you use where clauses it creates the exact query it needs, but with IEnumerable it retrieves all rows from database and then filters on memory.

The exact question here: Is this the same?

How is the better way?

public ActionResult Index()
        {
            var positions = unitOfWork.PositionRepository.Find(p => p.PositionID != null);

            return View(positions.ToList());
        }

 public ActionResult Index()
        {

            IQueryable<positions> positions = unitOfWork.PositionRepository.Find(p => p.PositionID != null);

            return View(positions.ToList());
        }

Upvotes: 0

Views: 440

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292465

var means that the type is automatically inferred by the compiler. Basically, if the data source is an IQueryable (e.g. an Entity Framework or Linq to SQL datacontext, a RIA service, etc), your variable will also be an IQueryable. If the data source is an IEnumerable (e.g. an in-memory collection of objects), your variable will also be an IEnumerable.

Since IQueryable<T> inherits from IEnumerable<T>, any IQueryable can be treated as an IEnumerable, by using the AsEnumerable extension method. Everything that follows the call to AsEnumerable will be executed locally rather than translated to the data source language (SQL, HTTP REST...).

Upvotes: 1

Related Questions