tesic

tesic

  • NA
  • 6
  • 0

BinarySearch problem...

Sep 30 2004 7:26 PM
Hello, I'm working on a small project and I have to search ArrayList that contains simple object list. This is my object: public class NameValue { private string strName; private string strValue; public NameValue( string sNameValuePair ) { StringTokenizer tok = new StringTokenizer( sNameValuePair, "=" ); this.strName = tok.nextElement().Trim(); this.strValue = tok.nextElement().Trim(); } private void splitName( StringTokenizer tok ) { this.strName = tok.nextElement(); string temp = this.strName; } public string Name { get { return strName; } set { strName = value; } } public string Value { get { return strValue; } set { strValue = value; } } } This is code where I call BinarySearch method: public ArrayList AddPairToList( string sNameValuePair ) { int nPos; NameValue nv = new NameValue( sNameValuePair ); SortByName(); nPos = a.BinarySearch( nv, new CompareCustomDataType() ); if( nPos < 0 ) { a.Add( nv ); } else { MessageBox.Show( "The item you tried to add to the list already exist!" ); } return GetCurrentList(); } And this is my CompareCustomDataType class: public class CompareCustomDataType : IComparer { public int Compare( object x, object y ) { if (x == null) return -1; if (y == null) return 1; NameValue xNameValue = (NameValue) x; NameValue yNameValue = (NameValue) y; if( xNameValue.Name.CompareTo( yNameValue.Name ) > 0 ) { return 1; } else if( xNameValue.Name.CompareTo( yNameValue.Name ) < 0 ) { return -1; } return String.Compare( xNameValue.Value, yNameValue.Value ); } } However, it doesn't work properly. Actually, my list seems like this: Australia = Canberra Austria = Wiena Canada = Toronto Canada = Ottawa ... When I try to add some pair to the list and if only unique pair already exist in the list (when I say unique pair I mean only one pair with unique name and unique value such as: Australia, Canberra) everything works fine, but when I try to add some pair to the list that already exist and if it is not unique pair (when I say "it is not unique pair" I mean I have pairs with the same name and different values such as: Canada, Toronto; Canada, Ottawa), first couple of times I get proper message "The item you tried to add to the list already exist!". After that, the object that already exist is added to the list and I have duplicate... Would you be so kind to help me to fix this problem... Thank you in advance, Goran Tesic

Answers (5)