I have a collection that contains a collection of attributes. Each attribute has a type and an Id. I need to filter the collection where the attribute ids are or’d within a group of attribute types but the attribute types are and’d. I came up with the following and wonder if there is a better way.
foreach (var ag in andAttrGrpIds)
{
filteredModels = filteredModels.Where(x => x.ProductAttributes.Any(pa => pa.AttributeType==ag && orAttributes.Contains(pa.AttributeId))).ToList();
}
In the above snippet, andAttrGrpIds and orAttributes are arrays of string.
I would do:
Now that’s more readable and (probably) has a better performance profile.
The idea is to get the set of all ‘qualifying’ product attribute-types from each model and then test if all the
andAttrGrpIdsare present in this set.By the way, your naming conventions seem quite strange: The
andAttrGrpIdscollection appears to actually represent a collection of attribute-types.