带有未分配变量参数的linq [英] linq with unassigned variable parameters

查看:63
本文介绍了带有未分配变量参数的linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主函数顶部有以下变量声明

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 value).

推荐答案

在构造LINQ查询之前,必须为变量分配一个值.

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.

这篇关于带有未分配变量参数的linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆