【发布时间】:2019-11-20 18:15:04
【问题描述】:
无论如何我可以将此代码优化为更短吗? MakeList、TrimList 等都是 List 类型。 和车辆是模型。 我的问题是代码很长。我在模型中有 20 个属性。
if (MakeList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => MakeList.Contains(b.Vehicle.Make));
}
if (TrimList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => TrimList.Contains(b.Vehicle.Trim));
}
if (ModelList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => ModelList.Contains(b.Vehicle.Model));
}
if (StockNoList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => StockNoList.Contains(b.Vehicle.StockNo));
}
if (BodyStyleList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => BodyStyleList.Contains(b.Vehicle.Body));
}
if (ExtColorList?.Any() == true)
{
bidVehicles = bidVehicles.Where(b => ExtColorList.Contains(b.Vehicle.Exterior));
}
return bidVehicles;
【问题讨论】:
-
MakeList, TrimList等是什么? -
@SeM - 他们是 List
先生。 -
短代码并不总是更容易理解,您可以删除与 ==true 的比较,除了我会寻找更多重构代码之外,您似乎正在构建一个动态 where 子句,看看你是否可以单独生成。
-
@peeyushsingh - 是的,我正在构建动态 where 子句。如果我重构它会附加太多参数。
-
问题是,您可以通过编写一些代码在技术上缩短这部分代码,这可能会或可能不会比这更长。
标签: c# entity-framework filter contains