Search Unity

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

Discussion in 'Scripting' started by guitarxe, Aug 22, 2014.

  1. guitarxe

    guitarxe

    Joined:
    Dec 1, 2013
    Posts:
    131
    Using C#, I have a List<Type> 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<T> 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?
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,692
    What about keeping track of the index of the currently-true item. That's O(1) versus O(n) for the foreach loop.
     
  3. schragnasher

    schragnasher

    Joined:
    Oct 7, 2012
    Posts:
    117
    No need to search
    Code (csharp):
    1.  
    2. myList.ForEach(e => e.myBool = !e.myBool);
    3.  
    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.
     
  4. guitarxe

    guitarxe

    Joined:
    Dec 1, 2013
    Posts:
    131
    Oh yeah, I didn't think of that haha. Thanks :)