简体   繁体   中英

Is there anyway I can optimize this code to much shorter?

Is there anyway I can optimize this code into shorter? MakeList, TrimList and etc are List type. and Vehicle are models. My problem is code is very long. I have 20 property in model.


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;

For LINQ to Objects:

public static class FilterExt
{
    public static IEnumerable<TItem> ApplyFilter<TProp, TItem>(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();

If you use EF (means bidVehicles is IQueryable ) you have to write expression for each property because you need full predicate Expression<Func<BidVehicle, bool>> not just Func<BidVehicle, TProp> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM