[英]How to use and if statement in linq Entity framework c#
I am declaring this variable to get data from my database(example)我声明这个变量是为了从我的数据库中获取数据(示例)
var products = _context.Products();
and I need to use like this example我需要像这个例子一样使用
if(ctId == -1)
{
// get project list
var products = _context.Products().where(a => a.categoryId == 2);
}
else
{
//get category list
var products = _context.Products().where(a => a.categoryId == 1);
}
but my problem how to declare var products
to using like this但我的问题是如何声明
var products
像这样使用
if(ctId == -1)
{
// get project list
products = _context.Products().where(a => a.categoryId == 2);
}
else
{
//get category list
products = _context.Products().where(a => a.categoryId == 1);
}
To the initial problem, you would declare an IQueryable<Product>
outside the if
scope对于最初的问题,您将在
if
范围之外声明一个IQueryable<Product>
IQueryable<Product> products = null;
if(ctId == -1)
products = _context.Products().where(a => a.categoryId == 2);
else
products = _context.Products().where(a => a.categoryId == 1);
However, you could also use a ternary conditional operator但是,您也可以使用三元条件运算符
The conditional operator
?:
, also known as the ternary conditional operator , evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates totrue
orfalse
.条件运算符
?:
,也称为三元条件运算符,计算布尔表达式并返回两个表达式之一的结果,具体取决于布尔表达式的计算结果是true
还是false
。The syntax for the conditional operator is as follows:
条件运算符的语法如下:
condition ? consequent : alternative
Example例子
var id = ctId == -1 ? 2 : 1;
var products = _context.Products().where(a => a.categoryId == id);
or potentially或潜在地
var products = _context.Products().where(a => a.categoryId == (ctId == -1 ? 2 : 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.