Simple class
public class Group
{
public Int16 ID { get; private set; }
public string Name { get; set; }
public Group ( Int16 id, string name )
{ ID = id; Name = name; }
}
What I would like is an ObservableCollection where the collection forces uniqueness on ID and CaseInsensitive uniqueness on Name.
What I tried is:
public class Group
{
public Int16 ID { get; private set; }
public string Name { get; set; }
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
Group g = obj as Group;
if ((System.Object)g == null)
{
return false;
}
// Return true if either fields match:
return ( ID == g.ID || string.Compare(Name, g.Name, true) == 0 ) ;
}
public bool Equals(Group g)
{
// If parameter is null return false:
if ((object)g == null)
{
return false;
}
// Return true if either fields match:
return ( ID == g.ID || string.Compare(Name, g.Name, true) == 0 ) ;
}
public override int GetHashCode()
{
return ID; // ^ (Int32)Name.ToLower();
}
public Group ( Int16 id, string name )
{ ID = id; Name = name; }
}
HashSet < Group >
That prevents adding a group with the same ID not doe not prevent adding a group with the same Name. And it does not stop renaming a Name to an existing Name.
It will take a little tweaking of your class but here is how to do it. First you need group to notify the collection that you are about to change the name, do this by adding a event and modifying the setter of Name.
First Add this Interface and event handeler.
Then have your class implement the interface
Then you will need a custom collection that listens for
TestForCollisionevents and handles accordingly. For most of the methods you can just call the parent_BaseSet‘s version, however for any of the methods that modify the set you will need to either subscribe or un-subscribe to the event. I have done Clear, Add and Remove for you.