[英]C#: How to define implicit type variable inside IF block and use outside
I want to do something like this: 我想做这样的事情:
var myQuery;
if (someParam > 0)
{
myQuery = from x in myTable where x.myValue > someParam select x;
}
else {
myQuery = from x in myTable select x;
}
The problem is I can't do this because you apparently cannot define an implicit variable without declaring it first, nor can you re-declare an implicit variable after you've declared it. 问题是我无法执行此操作,因为您显然无法先定义隐式变量而未先声明它,也无法在声明它后重新声明隐式变量。
Assuming that I will not know the return type of the data (the whole point of an implicit type variable), what's the appropriate way to do this? 假设我不知道数据的返回类型(隐式类型变量的整个要点),执行此操作的合适方法是什么?
EDIT: 编辑:
The first answer below works well if your types are clearly defined, but what about something like this? 如果明确定义了您的类型,则下面的第一个答案会很好用,但是这样的事情呢?
var myQuery;
if (includeSomething == true)
{
myQuery = from x in myTable select new { f1 = x.field1, f2 = x.field2 };
}
else {
myQuery = from x in myTable select new { f1 = x.field1, f2 = x.field2, x3 = x.field3 };
}
Yes, in such case declare it strongly typed like 是的,在这种情况下,请声明它为强类型
var myQuery;
to 至
IEnumerable<your_type> myQuery;
You can as well do this using a ternary operator like 您也可以使用三元运算符
var myQuery = (someParam > 0) ? from x in myTable where x.myValue > someParam select x : from x in myTable select x;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.