How to use Comparer for a HashSet

A HashSet doesn’t need a IComparer<T> – it needs an IEqualityComparer<T>, such as

public class SynonymComparer : IEqualityComparer<Synonym>      
{
   public bool Equals(Synonym one, Synonym two)
   {
        // Adjust according to requirements.
        return StringComparer.InvariantCultureIgnoreCase
                             .Equals(one.Name, two.Name);

   }

   public int GetHashCode(Synonym item)
   {
        return StringComparer.InvariantCultureIgnoreCase
                             .GetHashCode(item.Name);

   }
}

However, your current code only compiles because you’re creating a set of comparers rather than a set of synonyms.

Furthermore, I don’t think you really want a set at all. It seems to me that you want a dictionary or a lookup so that you can find the synonyms for a given name:

public class SynonymManager
{ 
    private readonly IDictionary<string, Synonym> synonyms = new
        Dictionary<string, Synonym>();

    private void Add(Synonym synonym)
    {
        // This will overwrite any existing synonym with the same name.
        synonyms[synonym.Name] = synonym;
    }

    public void SomeFunction()
    { 
        // Just a function to add 2 synonyms to 1 stock.
        Stock stock = GetStock("General Motors");
        Synonym otherName = new Synonym("GM", stock);
        Add(otherName);
        ListOfSynonyms.Add(otherName);
        otherName = new Synonym("Gen. Motors", stock);
        Add(otherName);
    }

    public Synonym Find(string nameSynonym)
    {
       // This will throw an exception if you don't have
       // a synonym of the right name.  Do you want that?
       return synonyms[nameSynonym];
    }
}

Note that there are some questions in the code above, about how you want it to behave in various cases. You need to work out exactly what you want it to do.

EDIT: If you want to be able to store multiple stocks for a single synonym, you effectively want a Lookup<string, Stock> – but that’s immutable. You’re probably best storing a Dictionary<string, List<Stock>>; a list of stocks for each string.

In terms of not throwing an error from Find, you should look at Dictionary.TryGetValue which doesn’t throw an exception if the key isn’t found (and also returns whether or not the key was found); the mapped value is “returned” in an out parameter.

Leave a Comment