The problem arises from the fact that the
Person
has a value changed that is involved with the comparison, but the
SortedSet
is unaware the value has changed. I couldn't find a way to fix this.
I tried the following code (to clarify for others what the problem is :
class Person: IComparable
{
public string Name { get; set; }
public int CompareTo(object obj)
{
Person objPerson = obj as Person;
return this.Name.CompareTo(objPerson.Name);
}
public Person(string name)
{
Name = name;
}
}
class Program
{
static SortedSet<person> sortedSet = new SortedSet<person>();
static void WriteElements()
{
foreach (Person foo in sortedSet)
Console.WriteLine(foo.Name);
}
static void Main(string[] args)
{
Person alice = new Person("Alice");
sortedSet.Add(new Person("Zelda"));
sortedSet.Add(new Person("Bob"));
sortedSet.Add(new Person("Mary"));
sortedSet.Add(alice);
alice.Name = "Zoe";
WriteElements();
Console.ReadKey();
}
}
Sadly, it looks like Microsoft have not given us a way to force the set to re-sort which would fix it.
There is nothing in the documentation telling you shouldn't change the properties in this way and it seems a very reasonable thing to do. You could raise this with them as it looks like a genuine bug!
My solution is to remove the item from the list, update it then re-insert for now. I hope someone has a better answer!
[Edit]
Mike Hankey[
^] has found a work around you can look at. It looks an option, if you don't mind the
INotify...
and
IObservable...
stuff