How to retrieve actual item from HashSet?

前端 未结 11 559
花落未央
花落未央 2020-12-02 17:55

I\'ve read this question about why it is not possible, but haven\'t found a solution to the problem.

I would like to retrieve an item from a .NET HashSet. I

11条回答
  •  盖世英雄少女心
    2020-12-02 18:38

    What about overloading the string equality comparer:

      class StringEqualityComparer : IEqualityComparer
    {
        public string val1;
        public bool Equals(String s1, String s2)
        {
            if (!s1.Equals(s2)) return false;
            val1 = s1;
            return true;
        }
    
        public int GetHashCode(String s)
        {
            return s.GetHashCode();
        }
    }
    public static class HashSetExtension
    {
        public static bool TryGetValue(this HashSet hs, string value, out string valout)
        {
            if (hs.Contains(value))
            {
                valout=(hs.Comparer as StringEqualityComparer).val1;
                return true;
            }
            else
            {
                valout = null;
                return false;
            }
        }
    }
    

    And then declare the HashSet as:

    HashSet hs = new HashSet(new StringEqualityComparer());
    

提交回复
热议问题