Enhanced IQueryable vs IEnumerable Extension Methods

Suppose I have a class that implements the IQueryable<> interface (which inherits IEnumerable<> ).

When I call the Where() method on it, the compiler resolves this call for IQueryable extensions, although IEnumerable extensions also have a Where() method.

The question is, how does the compiler understand which extension should be called?

+5
source share
2 answers

The C # specification described:

7.5.3.5 Best conversion goal

Given the two different types T1 and T2 , T1 is a better conversion target than T2 if at least one of the following conditions is true:

  • There is an implicit conversion from T1 to T2 , and there is no implicit conversion from T2 to T1

  • T1 is a signed integral type, and T2 is an unsigned integral type.

Since there is an implicit conversion from IQueryable<T> to IEnumerable<T> , and there is no implicit conversion from IEnumerable<T> to IQueryable<T> , IQueryable<T> is the best conversion target and takes precedence.

+14
source

Methods of expanding early communication.

With sample code:

 //db is an instace of EntityFramework DbContext IQueryable<EntityClass1> query1 = db.EntityClassTable1.Where(x => 1 == 1); IEnumerable<EntityClass1> query2 = db.EntityClassTable1.Where(x => 1 == 1); var result1 = query1.Where(x => 1 == 1); var result2 = query2.Where(x => 1 == 1); 

Although the dynamic types query1 and query2 IQueryable<EntityClass1> , the type result1 will be IQueryable<EntityClass1> , and the type result2 will be IEnumerable<EntityClass1> due to early binding.

-1
source

Source: https://habr.com/ru/post/1200721/


All Articles