You can override Equals
and GetHashCode
to not only compare references what Object.Equals
does:
public class VersionSettings
{
public String Culture { get; set; }
public String Domain { get; set; }
public String Name { get; set; }
public override bool Equals(object obj)
{
VersionSettings other = obj as VersionSettings;
if(other == null) return false;
return Culture == other.Culture;
}
public override int GetHashCode()
{
return Culture == null ? 0 : Culture.GetHashCode();
}
}
Another approach is to implement a custom IEqualityComparer<VersionSettings>
which does not require to modify the class itself:
public class VersionSettingComparer : IEqualityComparer<VersionSettings>
{
public bool Equals(VersionSettings x, VersionSettings y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.Culture == y.Culture;
}
public int GetHashCode(VersionSettings obj)
{
if(obj == null) return 0;
return obj.Culture == null ? 0 : obj.Culture.GetHashCode();
}
}
Now you can use the constructor of HashSet<T>
:
var vs = new HashSet<VersionSettings>(new VersionSettingComparer());
According to your second question how you can access the HashSet<VersionSetting>
in this way:
var enUsSetting = vs["en-US"];
That doesn't work because a hashset has no indexer like a collection or dictionary. You probably want a Dictionary<string, VersionSettings>
instead.
As simple but not that efficient workaround you can use LINQ:
var enUsSetting = vs.FirstOrDefault(x => x.Culture == "en-US");
If you want to create the mentioned dictionary you can also use LINQ:
Dictionary<string, VersionSettings> cultureLoookup = vs
.ToDictionary(x => x.Culture, x => x); // you only need to create this once
Now this works:
var enUsSetting = cultureLoookup["en-US"];