Is there a performance optimized search method for List<T>?

Using C#, I have a List with several objects. All objects of this type have a bool, but requirements are that only one object can have that bool set to true at any one time.

So when I am setting the bool to true to one of the objects, I want to go through the list and set the bool for the rest to false.

Since only one object will have the bool set to true in the list, are any of the List class methods optimised to do this kind of search quickly, or should I just go through all the objects one by one with a simple foreach loop?

What about keeping track of the index of the currently-true item. That’s O(1) versus O(n) for the foreach loop.

No need to search

myList.ForEach(e => e.myBool = !e.myBool);

Or do as TonyLi said keep a reference to the “true” element outside of the list then just switch it to false before switching the new element to true and then set it as the new reference. It sort of depends on how you are deciding who is the new “true” element.

Oh yeah, I didn’t think of that haha. Thanks :slight_smile: