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