我只是想听听是否有更简单的方法。
public void Model(string _model)
{
var list =
from vehicle in vehiclesorted
where vehicle.Model == _model
orderby vehicle.Price
select vehicle;
vehiclesorted = list.ToList();
}
public void Brand(string _brand)
{
var list =
from vehicle in vehiclesorted
where vehicle.Brand == _brand
orderby vehicle.Price
select vehicle;
vehiclesorted = list.ToList();
}
public void Mph(int _mph)
{
var list =
from vehicle in vehiclesorted
where vehicle.Mph <= _mph
orderby vehicle.Price
select vehicle;
vehiclesorted = list.ToList();
}
答案 0 :(得分:5)
您可以将此重构为一个采用谓词进行过滤的方法:
private void CreateSortedList(Func<Vehicle, bool> predicate)
{
vehiclesorted = vehiclesorted.Where(predicate).OrderBy(v => v.Price).ToList();
}
然后调用成为:
public void Mph(int _mph)
{
CreateSortedList(v => v.Mph <= _mph);
}
public void Brand(string _brand)
{
CreateSortedList(v => v.Brand == _brand);
}
话虽这么说,制作多个公共方法,每个过滤一个私有集合看起来像一个奇怪的设计选择,特别是因为后续调用过滤以前过滤的结果。您可能希望每次都过滤原始列表。
考虑返回过滤后的结果而不是每次调用都会改变内部列表通常也是个好主意。这将提供更清晰的API,并在使用此类时减少意外。
答案 1 :(得分:3)
我在您的代码中看到的问题:
FilterByModel
,FilterByBrand
等方法vehiclesorted
为List
?将其存储为IEnumerable<Vehicle>
代替,只有在需要读取其值时才将其转换为List
。vehiclesorted
不是一个很好的名字 - vehiclesSorted
怎么样?所以这就是我如何重构这些方法:
private IEnumerable<Vehicle> vehiclesSorted;
public void FilterByModel(string _model)
{
vehiclesSorted = vehiclesSorted.Where(v => v.Model == _model);
}
public void FilterByBrand(string _brand)
{
vehiclesSorted = vehiclesSorted.Where(v => v.Brand == _brand);
}
public void Mph(int _mph)
{
vehiclesSorted = vehiclesSorted.Where(v => v.Mph <= _mph);
}
public List<Vehicle> Vehicles {
get {
return vehiclesSorted.ToList();
}
}