Linq嵌套集合过滤器

时间:2017-12-21 16:54:44

标签: c# linq

我有RefersTo:=Range("Sales"!$A$" & rngCell.Row)Brand个查看模型,其中包含各自的AreaId视图模型的集合为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); } } } 个集合,其SelectedAreasId匹配。

我收集了AreaViewModel。我希望得到BrandViewModel的集合,该集合由选定区域过滤。 尝试下面的陈述,但BrandViewModel条款需要一个bool条件。

Where

2 个答案:

答案 0 :(得分:2)

您可以将内部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) {1}}:

var hash = new HashSet<int>(SelectedAreas.Select(s => s.Id));
filteredBrandViewModels = brandViewModels.Where(b => b.Areas.Any(a => hash.Contains(a.Id)));

答案 1 :(得分:0)

可枚举AnyIntersect的Linq方法将非常方便:

filteredBrandViewModels = brandViewModels.Where(b =>
    b.Areas.Select(a=>a.Id).Intersect(SelectedAreas.Select(sa => sa.Id).Any()
)