我在if
语句中定义一个变量,然后尝试在该语句的上下文之外使用该变量。如何在if语句之外初始化空dbSet
,以便viewModel
可以查看/填充它?
这就是我想要完成的事情:
if (order.type.ToString() == "Rush")
{
var filteredOrders = db.Orders.Where(a => a.rushID == order.rushID).ToList();
}
else if (order.type.ToString() == "Standard")
{
var filteredOrders = db.Orders.Where(a => a.standardID == order.standardID).ToList();
}
else
{
return HttpNotFound();
}
var viewModel = new OrderDetailsViewModel
{
PastOrders = filteredOrders, // filteredOrders doesn't exist here
Order = order;
};
答案 0 :(得分:1)
IEnumerable<Order> filteredOrders; // or IList<Order>, etc., as your prefer
switch (order.type.ToString())
{
case "Rush":
filteredOrders = db.Orders.Where(a => a.rushID == order.rushID).ToList();
case "Standard":
filteredOrders = db.Orders.Where(a => a.standardID == order.standardID).ToList();
default::
return HttpNotFound();
}
var viewModel = new OrderDetailsViewModel
{
PastOrders = filteredOrders,
Order = order;
};
或更好:
Func<Order, bool> filter;
switch (order.type.ToString())
{
case "Rush":
filter = a => a.rushID == order.rushID;
case "Standard":
filter = a => a.standardID == order.standardID;
default::
return HttpNotFound();
}
var viewModel = new OrderDetailsViewModel
{
PastOrders = db.Orders.Where(filter).ToList(),
Order = order;
};