c# - Is there a better way to search a list with another list -
is there better linq query see if list contains item in list following:
results.where(r => r.categories.intersect(submittedcategories).count() > 0) where r.categories list of categories result in , submittedcategories list of categories user want filter on
i use enumerable.any instead of enumerable.count:
results.where(r => r.categories.intersect(submittedcategories).any()) method count() has optimization sources implement icollection (it returns count property value of collection). result of enumerable.intersect ienumerable<t> in case count() iterate on set:
public static int count<tsource>(this ienumerable<tsource> source) { if (source == null) throw error.argumentnull("source"); icollection<tsource> is2 = source icollection<tsource>; if (is2 != null) return is2.count; icollection is3 = source icollection; if (is3 != null) return is3.count; int num = 0; using (ienumerator<tsource> enumerator = source.getenumerator()) { while (enumerator.movenext()) // fall case num++; } return num; } it means full intersection should built both collections know total count of items in result. , value compared zero.
any() stop iterating after first item found without finding items intersect.
public static bool any<tsource>(this ienumerable<tsource> source) { if (source == null) throw error.argumentnull("source"); using (ienumerator<tsource> enumerator = source.getenumerator()) { if (enumerator.movenext()) return true; } return false; } another benefit - any() shows intent better.
Comments
Post a Comment