I have some code that filters through a collection of sorted objects according to a filter value. For instance, I want to find the objects where Name=="searchquery". Then I want to take the top X values from that collection.
My questions:
-
My collection is a
List<T>. Does this collection guarantee the sort order? -
If so, is there a built-in way to find the the top X objects that satisfy the condition? I’m looking for something like
collection.FindAll(o=>o.Name=="searchquery",100);That would give me the top 100 objects that satisfy the condition. The reason is performance, once I’ve found my 100 objects, I don’t want to keep checking the entire collection.
-
If i write:
collection.FindAll(o=>o.Name=="searchquery").Take(100);will the runtime be intelligent enough to stop checking once it hits 100?
I can of course implement this myself, but if there is a built-in way (like a LInQ method) I’d prefer to use it.
The order should be in the same order as the original list, and it will stop checking once it takes 100 elements (
Wherereturns an enumeration which is only evaluated as you take elements). From the documentation:If you need a different sort order, you will have to specify it (this of course means you have no choice but to examine all elements though).