IQueryable Conversions

Why is conversion possible in the string "OK" and not in the string "NOT OK"?

var queryable = new int[]{1, 2, 3}.AsQueryable();

var x = (Expression<Func<IQueryable<int>>>)(() => (from c in queryable select c));

var yy = (Expression<Func<IEnumerable<int>>>)x;  // NOT OK (does not compile)
var zz = (Expression<Func<IEnumerable<int>>>)(() => (from c in queryable select c)); // OK

Update: error message:

Cannot convert type System.Linq.Expressions.Expression<System.Func<System.Linq.IQueryable<int>>>to System.Linq.Expressions.Expression<System.Func<System.Collections.Generic.IEnumerable<int>>>

+4
source share
2 answers

Because Expression- this is a class, but IEnumerable- this is an interface. And classes are not covariant, but interfaces and delegates.

This means that you cannot convert Expression<A>to Expression<B>, even if B is the base class of A.

So if this line:

() => (from c in queryable select c)

returns

Func<IQueryable<int>>

it can be converted to

Func<IEnumerable<int>>

but if you already have

Expression<Func<IQueryable<int>>>

it cannot be converted to

Expression<Func<IEnumerable<int>>>
+3

Expression<T> .

:

Func<IQueryable<int>> qf = () => queryable.Select(c => c);
Func<IEnumerable<int>> ef = qf;

, #, Expression<T> Expression<U>, T to U;

+1

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


All Articles