简体   繁体   中英

Is there a better or more efficient way to filter with linq

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:

var filteredModels = from model in originalModels

                     let mAttribs = from pa in model.ProductAttributes
                                    where orAttributes.Contains(pa.AttributeId)
                                    select pa.AttributeType

                     where !andAttrGrpIds.Except(mAttribs).Any()

                     select model;

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 andAttrGrpIds are present in this set.

By the way, your naming conventions seem quite strange: The andAttrGrpIds collection appears to actually represent a collection of attribute- types .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM