2

How do I use an update method in C5 collection?

For example, lets say I have a set where I want to replace item A with B. I'd expect it to be something like:

HashSet<String> s = new HashSet<String>();
s.add("A");
s.update("A", "B");

but instead, Update takes a single parameter, and the documentation has the following to say:

bool Update(T x) returns true if the collection contains an item equal to x, in which case that item is replaced by x; otherwise returns false without modifying the collection. If any item was updated, and the collection has set semantics or DuplicatesByCounting is false, then only one copy of x is updated; but if the collection has bag semantics and DuplicatesByCounting is true, then all copies of the old item are updated. If any item was updated, then events ItemsRemoved, ItemsAdded and CollectionChanged are raised. Throws Read- OnlyCollectionException if the collection is read-only.

Any ideas? Thanks.

Andriy Drozdyuk
  • 58,435
  • 50
  • 171
  • 272

2 Answers2

2

I think you need to do this with two separate operations:

s.Remove("A");
s.Add("B");

The Update method only works if the two items are considered equal (two different objects can be equal). But "A" and "B" are not equal.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • @drozzy: Use it if you want to change one object for another, when they are equal. I guess you want an example? Ummm... I don't know... How about this... You might want to update a string with another string from the intern pool, to save memory. `s.Update(string.Intern(x));`. The string refered to by `x` and the result of `string.Intern(x)` could potentially be different string objects, but they would have equal values. You could of course ask why you didn't just intern them in the first place, before inserting? I don't have a good answer for that, but this is just an example. – Mark Byers May 29 '12 at 18:36
0

An item in the set is "Update"d if the target is matched based on equality (with hash considerations). It is not "Replace". That is, the implicit noun in the "Update" method refers to a specific item and not the HashSet itself.

For instance if the HashSet is being used as a database cache, the equality of a mapped database object might be cover only the Primary Key. As seen, "Update" doesn't make much sense for many trivial types, and might not even make much sense outside of a specific SGC.IEqualityComparer used for a given HashSet object. (That is, outside of this particular HashSet, the equality of said database object might cover all the values.)

See the section "Equality and comparison" (2.1) and the HashSet constructor (6.10).

Happy coding.