开发者

linq with unassigned variable parameters

I have the following variable declarations at the top of my main function

string brand;
double price;
var itemList6 = from i in myStore.items
    where i.price <= price && i.brand == brand
    orderby i.type
    select i;

Later on in the program I ask the user for a brand and a price, put them in the appropriate variables, and then run the query. However, the compiler won't let me run this, because I am using unassigned variables in the query. Is the only way to solve this by initializing the variables? I generally try to not initialize variable if I don't need an initial value since I find it confusing (trying to understand later where/why I used that default valu开发者_如何学Ce).


You could write a function and pass those variables as parameters to avoid intialization..

Also in case you end up initializing consider using ?? in order to avoid nulls.


You have to assign a value to the variables before you construct the LINQ query.

The reason is that the compiler is using the variables to construct the query. Even though the query won't be executed, the compiler requires variables to be assigned before use, and the compiler sees building the query expression as use.

My recommendation is just to put some nominal default/temp value in there.


Another way to solve it is to not create the query object until after you have definitely assigned values to those variables.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜