I use dictionary in my program like this
Dictionary<string, List<Term>>
which Term is object from class has two fields (name , id)
I need add new object into dictionary where the name of new object is not found in the dictionary…
if the field name in new object is existent as name of old object I will not add it..
can you help me
the code I use is
foreach (string term in terms)
{
if (!dictionary.ContainsKey(term))
{
dictionary.Add(term, new List<Term>());
}
Term TT=new Term(i,name);
if (!dictionary[term].Contains(TT))
{
dictionary[term].Add(TT);
}
this code dosn’t work exactly..
The problem is here:
The default behavior of
List.Containsif classTermdoes not implementIEquatable<Term>is to check for reference equality. Since the object you just constructed cannot already be in the list,Containswill always returnfalseand the newTermwill always be added.One good solution would be to implement
IEquatable<Term>inTermand specify the criteria you want for equality in theIEquatable<Term>.Equalsmethod.Another solution (which is probably less desirable because it will only help this particular piece of code to work) is to change the test to