[英]Linq nested collection filter
我有包含各自Id
的Brand
和Area
视图模型。 Brand
视图模型具有Areas
的集合。
public class BrandViewModel
{
public int Id { get; set; }
private ObservableCollection<AreaViewModel> _areas;
public ObservableCollection<AreaViewModel> Areas
{
get { return _areas; }
set { Set(() => Areas, ref _areas, value); }
}
}
我有SelectedAreas
集合,该集合具有与AreaViewModel
匹配的Id
。
我有BrandViewModel
集合。 我想收集按选定区域过滤的BrandViewModel
。 尝试过以下语句,但Where
子句需要bool条件。
filteredBrandViewModels = brandViewModels.Where(b => b.Areas
.Where(a => SelectedAreas.Select(sa => sa.Id).Contains(a.Id)));
您可以替换内Where
有Any
:
filteredBrandViewModels = brandViewModels.Where(b =>
b.Areas.Any(a => SelectedAreas.Select(sa => sa.Id).Contains(a.Id)));
然后,您还可以将“ Select
更改为:
filteredBrandViewModels = brandViewModels.Where(b =>
b.Areas.Any(a => SelectedAreas.Any(sa => sa.Id == a.Id)));
最后,在有大量数据的情况下,我建议将SelectedAreas
中的id作为HashSet<int>
这样搜索将是O(n)
操作而不是O(n^2)
:
var hash = new HashSet<int>(SelectedAreas.Select(s => s.Id));
filteredBrandViewModels = brandViewModels.Where(b => b.Areas.Any(a => hash.Contains(a.Id)));
可枚举Any
和Intersect
Linq方法在这里很方便:
filteredBrandViewModels = brandViewModels.Where(b =>
b.Areas.Select(a=>a.Id).Intersect(SelectedAreas.Select(sa => sa.Id).Any()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.