无论如何,我可以将这段代码优化得更短吗?

时间:2019-07-11 05:36:12

标签: c# entity-framework filter contains

总有没有可以将这段代码优化为更短的代码? MakeList,TrimList等是列表类型。 和车辆是模型。 我的问题是代码很长。我的模型有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;

1 个答案:

答案 0 :(得分:3)

对于LINQ to Objects:

public static class FilterExt
{
    public static IEnumerable<TItem> ApplyFilter<TProp>(this IEnumerable<TItem> list, List<TProp> filter, Func<TItem, TProp> prop)
    {
        if (filter == null || filter.Count == 0)
        {
            return list;
        }

        return list.Where(x => filter.Contains(prop.Invoke(x)));
    }
}

...

var filtered = bidVehicles
    .ApplyFilter(MakeList, x => x.Vehicle.Make)
    .ApplyFilter(TrimList, x => x.Vehicle.Trim).ToList();

如果您使用EF(表示bidVehiclesIQueryable),则必须为每个属性编写表达式,因为您需要完整的谓词Expression<Func<BidVehicle, bool>>,而不仅仅是Func<BidVehicle, TProp>