Re: Key compare in Dictionary
Ryan Heath <[email protected]> Thu, 20 May 2010 12:48:03 +0200
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Message-ID | <[email protected]> |
I always override Object.GetHashCode and Object.Equals for these sorts of things ... // Ryan On Thu, May 20, 2010 at 12:32 PM, David Nicholson <[email protected]> w= rote: > I am using a class as a key to a Dictionary, and the key comparisons are = not working as I expect. The example below illustrates: > > // This is the key of the dictionary > namespace DictionaryTest > { > =A0 =A0using System; > =A0 =A0public class KeyData : IEquatable<KeyData> > =A0 =A0{ > =A0 =A0 =A0 =A0public string F1 { get; set; } > =A0 =A0 =A0 =A0public int F2 { get; set; } > > =A0 =A0 =A0 =A0public KeyData(string f1, int f2) > =A0 =A0 =A0 =A0{ > =A0 =A0 =A0 =A0 =A0 =A0F1 =3D f1; > =A0 =A0 =A0 =A0 =A0 =A0F2 =3D f2; > =A0 =A0 =A0 =A0} > > =A0 =A0 =A0 =A0bool IEquatable<KeyData>.Equals(KeyData other) > =A0 =A0 =A0 =A0{ > =A0 =A0 =A0 =A0 =A0 =A0if (String.Compare(F1, other.F1, true) !=3D 0) > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0return false; > > =A0 =A0 =A0 =A0 =A0 =A0if (F2 !=3D other.F2) > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0return false; > > =A0 =A0 =A0 =A0 =A0 =A0return true; > =A0 =A0 =A0 =A0} > =A0 =A0} > } > > and I am using it like this: > > namespace DictionaryTest > { > =A0 using System; > =A0 using System.Collections.Generic; > =A0 =A0class Program > =A0 =A0{ > =A0 =A0 =A0 =A0static void Main(string[] args) > =A0 =A0 =A0 =A0{ > =A0 =A0 =A0 =A0 =A0 =A0var d1 =3D new Dictionary<KeyData, int>(); > > =A0 =A0 =A0 =A0 =A0 =A0d1.Add(new KeyData("a", 1), 1); > =A0 =A0 =A0 =A0 =A0 =A0d1.Add(new KeyData("b", 1), 1); > > =A0 =A0 =A0 =A0 =A0 =A0KeyData kd =3D new KeyData("a", 1); > > =A0 =A0 =A0 =A0 =A0 =A0string mesg; > =A0 =A0 =A0 =A0 =A0 =A0if (d1.ContainsKey(kd)) > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0mesg =3D "Found"; > =A0 =A0 =A0 =A0 =A0 =A0else > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0mesg =3D "Not found"; > > =A0 =A0 =A0 =A0 =A0 =A0Console.WriteLine(mesg); > =A0 =A0 =A0 =A0} > =A0 =A0} > } > > This always returns "Not found", which isn't what I expect. A breakpoint = on KeyData.Equals is never reached. The documentation for dictionary includ= es: > > "If type TKey implements the System .IEquatable <T> generic interface, th= e default equality comparer uses that implementation" > > I wrote an IEqualityComparer<KeyData> and passed that to the dictionary c= onstructor, and it works as I expect. > > Thanks > David. > > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > View archives and manage your subscription(s) at http://peach.ease.lsoft.= com/archives > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives