这是我的代码:
// I STORE THE USER SELECTED VALUES
IList<string> SelectedCity = (from CheckBox loc in panelCity.Controls.OfType<CheckBox>()
where loc.Checked
select loc.InputAttributes["value"]).ToList();
IList<string> SelectedCategories = (from CheckBox strut in panelCategories.Controls.OfType<CheckBox>()
where strut.Checked
select strut.InputAttributes["value"]).ToList();
// I GET ALL RECORDS
IList<Hotel> Hotels = (from Hotel hotel in new Hotels()
orderby hotel.Titolo ascending
select hotel).ToList();
// I FILTER THEM
if (SelectedCity.Count > 0)
Hotels = Hotels.Where(o => o.City != null && SelectedCity.Contains(o.City.UniqueID)).ToList();
if (SelectedCategories.Count > 0)
Hotels = Hotels.Where(o => o.Category != null && SelectedCategories.Contains(o.Category.UniqueID)).ToList();
因此,如您所见,我进行了一些查询,存储了从用户那里选择的值。然后,对于每一行酒店,我循环 City 和 Category 的数组。
这个,有很多行,非常昂贵。
您知道优化研究的其他一些方法吗?
最佳答案
将您的城市和类别放入 HashSet<string>
节省查找时间:
HashSet<string> selectedCities = new HashSet<string>(SelectedCity);
HashSet<string> selectedCategories = new HashSet<string>(SelectedCategories);
你也不需要使用 ToList()
直到您的查询完全组装好,否则您将遍历多次:
var hotels = from Hotel hotel in new Hotels()
select hotel;
if (SelectedCity.Any())
hotels = hotels.Where(o => o.City != null && selectedCities.Contains(o.City.UniqueID));
if (SelectedCategories.Any())
hotels = hotels.Where(o => o.Category != null && selectedCategories.Contains(o.Category.UniqueID));
最后,一旦您过滤掉所有您不想要的酒店就可以进行排序,因此您排序的项目较少:
hotels = hotels.OrderBy(h=> h.Titolo);
作为最后一步,实现结果:
Hotels = hotels.ToList();
关于c# - 您知道执行此 "massive"linq 过滤的另一种方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9602766/