简体   繁体   中英

conditional linq query behavior

I have a feeling the title is misleading, please edit if you choose to. when I do this:

var q  = (condition)?(from ...Select(..)): (from.. Select(..));

I get a error at ":" saying

Type of conditional expression could not be determined because 
there is no implicit conversion between anonymous types. 

But if I do:

var b = some base linq query;
var q = (condition)?(use b here one way):(use b here differently);

no complaints. Why? How is second way different?

Edit:

Everywhere, my final projections are the same. (Final .Select(....) everywhere has same fields)

Edit2:

I apologize.. typo on my part. Select()s everywhere were not the same. Method 1 works fine too if the projections 'match'

If you did a cast after your LINQ query everything would be fine.

Its sort of the same problem that you get then you do something like

int? val = true ? 1 : null;

That won't work, but if you cast the null like this:

int? val = true ? 1 : (int?)null;

It does.

A conditional expression needs the two operands it's evaluating to be the same type. So if you do

var a = (condition)? "A" : "B";

... both "A" and "B" are of the same type (string), so the result, a , will be of type string .

What your error message is telling you is that your two operands (the two from ... Select statements) evaluate to anonymous types, but not the same anonymous type, and it can't convert one anonymous type into another. Thus it doesn't know what type the result, q , should be.

While I am not 100% sure, I believe that even if your two expressions are exactly the same, they will be different anonymous types. At any rate, the fact that you got that error indicates that they are not the same anonymous type.

With your second set of statements, you first set b to be equal to the result of a linq query. Hence it has a type. Although your statement does say so, the fact that the code compiles implies that (use b here one way) and (use b here differently) return results of the same type. If they both return an instance of the same type as b , for example, they will be of the same type.

It think the error message explains this:

Type of conditional expression could not be determined because there is no implicit conversion between anonymous types.

This

var x = 0 < 2 ? new { a = 1 } : new { a = 2 }

would compile. but this

var x = 0 < 2 ? new { a = 1 } : new { b = 2 };

would give the error above because {a=1} and {b=2} are not the same anonymous types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM