如何使用的Comparer为HashSet的 [英] How to use Comparer for a HashSet

查看:143
本文介绍了如何使用的Comparer为HashSet的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于其他问题,我在这里问我想用一个HashSet的我对象的结果

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.

public class Synonym
{
   private string name;
   private Stock owner;
   public Stock(string NameSynonym, Stock stock)
   {
       name=NameSynonym;
       owner=stock
   }
   // [+ 'get' for 'name' and 'owner']
}

我明白我需要一个比较器,但在此之前从未使用过它。我应该创建一个单独的类?这样的:

I understand I need a comparer , but never used it before. Should I create a separate class? like:

public class SynonymComparer : IComparer<Synonym>
{
   public int Compare(Synonym One, Synonym Two)
   { // Should I test if 'One == null'  or  'Two == null'  ???? 
       return String.Compare(One.Name, Two.Name, true); // Caseinsesitive
   }



}

}

我宁愿有一个函数(或者,如果需要嵌套类[也许是单身?])是类同义词,不是另一个(独立)类的一部分。这是可能的。

I prefer to have a function (or nested class [maybe a singleton?] if required) being PART of class Synonym instead of another (independent) class. Is this possible?

关于用法:
之前,我想我必须写一个查找(字符串NameSynonym)正如我从来没有使用过这种事情函数类的同义词内?,但我应该怎么办

About usage: As i never used this kind of thing before I suppose I must write a Find(string NameSynonym) function inside class Synonym, but how should I do that?

public class SynonymManager
{ 
    private HashSet<SynonymComparer<Synonym>> ListOfSynonyms;

    public SynonymManager()
    {
        ListOfSymnonyms = new HashSet<SynonymComparer<Synonym>>();
    }

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

    public Synonym Find(string NameSynomym)
    {
       return ListOfSynonyms.??????(NameSynonym);
    }
 }

在上面的代码,我不知道该怎么贯彻落实查找的方法。我应该怎么做呢?

In the code above I don't know how to implement the 'Find' method. How should i do that?

任何帮助将不胜感激
(PS。如果我对应该如何执行的想法是完全错误的,让我知道,告诉我如何实现)

Any help will be appreciated (PS If my ideas about how it should be implemented are completely wrong let me know and tell me how to implement)

推荐答案

一个HashSet中不需要的IComparer< T> - 它需要一个的IEqualityComparer< T> ,如

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);

   }
}



不过,您目前的代码只编译因为你创建一组的 comparers 的,而不是一组的同义词

此外,我不认为你真的想要一个组的。您要一本字典或查找,这样你可以找到一个给定名称的同义词在我看来:

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.

编辑:如果你希望能够存储多个股票为单个同义词,你的有效的希望有一个查找<字符串,股票> - 但那是不可变的。你可能最好的存储词典<字符串列表<股票及GT;> ;库存量为每个字符串列表。

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.

在没有从查找抛出错误方面,你应该看看 Dictionary.TryGetValue 如果没有找到键(也返回与否的关键的的发现)不抛出异常;在输出参数映射值返回。

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.

这篇关于如何使用的Comparer为HashSet的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆