Link to home
Start Free TrialLog in
Avatar of Ameerh24
Ameerh24

asked on

how use binary search to fine element in list then remove this element?

hi,
in c# .net 2008,
suppose I have List (dailySnapshotList ) of this class (DailySnapshot) :
    public partial class Main : Form
    {
        public static List<DailySnapshot> dailySnapshotList = new List<DailySnapshot>();
........
........
........

}

    public class DailySnapshot
    {
        public Bitmap bDailySnapshot = null;
        public string sDailySnapshot = null;
        public DailySnapshot(Bitmap bDailySnapshot, string sDailySnapshot)
        {
            this.bDailySnapshot = bDailySnapshot;
            this.sDailySnapshot = sDailySnapshot;
        }
    }

somewhere in my code, I need to check all object (in type of DailySnapshot) of this list (dailySnapshotList ) if the string parameter (sDailySnapshot ) of the class (DailySnapshot) contained in the list (dailySnapshotList ), so I need to remove this element from the list

so I try this:

                                if (dailySnapshotList.Contains(new DailySnapshot(null, "test")))
                                {
                                }
but its not working ........

a friend of mine told me to use binary search, so how can I use it ??

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also, the reason your original code doesn't work is that you are checking for a particular INSTANCE:

    if (dailySnapshotList.Contains(new DailySnapshot(null, "test")))

Since you passed in a NEW instance it will of course never be found in the List...

Without LINQ, you could iterate over each instance in the List and check equality based on the FIELDS.

Or you could use the Find() method of your List and pass it a Predicate.
Using your existing code, I believe the Contains() method is overloaded to accept a comparer object, which you could code to check your fields, as Idle_Mind suggested.

http://msdn.microsoft.com/en-us/library/system.collections.comparer(VS.71).aspx
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial