How to use Comparer for a HashSet

后端 未结 3 2176
长情又很酷
长情又很酷 2020-12-03 21:39

As a result of another question I asked here I want to use a HashSet for my objects

I will create objects containing a string and a reference to its owner.

3条回答
  •  没有蜡笔的小新
    2020-12-03 22:29

    You can always use LINQ to do the lookup:

    public Synonym Find(string NameSynomym)
    {
       return ListOfSynonyms.SingleOrDefault(x => x.Name == NameSynomym);
    }
    

    But, have you considered using a Dictionary instead, I believe it is better suited for extracting single members, and you can still guarantee that there are no duplicates based on the key you choose.

    I am not sure that lookup time is of SingleOrDefault, but I am pretty sure it is linear (O(n)), so if lookup time is important to you, a Dictionary will provide you with O(1) lookup time.

提交回复
热议问题