如何改写C#代码检查字典列表中所有StructureData子类元素
解决方案
你需要把原来只检查列表第一个元素的逻辑,改成遍历整个列表的判断:
筛选完全不含NatureStructureData的IntBound
把原来的FirstOrDefault()判断换成All()方法,确保列表里所有元素都不是NatureStructureData:
public IEnumerable<IntBound> GetBoundsWithStructuresWithoutNatureWithin(IntBound selectionBounds) { return structuresDataCollection .Where(s => s.Key.Intersects(selectionBounds)) .Where(s => s.Value.All(item => item is not NatureStructureData)) .Select(s => s.Key); }
筛选存在NatureStructureData的IntBound
把原来的FirstOrDefault()判断换成Any()方法,只要列表里存在至少一个NatureStructureData就符合条件:
public IEnumerable<IntBound> GetBoundsWithNatureWithin(IntBound selectionBounds) { return structuresDataCollection .Where(s => s.Key.Intersects(selectionBounds)) .Where(s => s.Value.Any(item => item is NatureStructureData)) .Select(s => s.Key); }
改动说明
All():会遍历列表所有元素,只有当所有元素都满足「不是NatureStructureData」的条件时,才返回true,正好匹配「完全不包含」的需求。Any():只要列表里有任意一个元素满足「是NatureStructureData」的条件,就返回true,匹配「存在至少一个」的需求。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

