Skip to main content

Microsoft Silverlight

Answered Question Collection methods not finding Strings within collectionRSS Feed

(0)

andrewjw
andrewjw

Member

Member

7 points

17 Posts

Collection methods not finding Strings within collection

In my application, the Items collection of a listbox is being filled with string values. At a later time, the application attempts to use other methods (Contains, IndexOf, Remove) to perform operations on the collection, but these wrongly report that the string value is not present in the listbox when it is.

(I am guessing that internally these methods use == to check equality rather than .Equals, with the result that they only identify strings as being present within the listbox if the string objects themselves are identical rather than if their string values are equal.)

Some example code showing the problem:

 

string a = new string(new char[] { 'h', 'e', 'l', 'l', 'o' });
string b = new string(new char[] { 'h', 'e', 'l', 'l', 'o' }); // a and b are unique string objects with identical values

listbox.Items.Add(a);
listbox.Items.Remove(b); // This fails to remove 'hello' from the listbox
  

bryant
bryant

Star

Star

9937 points

1,629 Posts

Silverlight MVP
Answered Question

Re: Collection methods not finding Strings within collection

A better option would be to use an observable collection and just perform the add/remove on that.

 

var strings = new ObservableCollection<string>() {"hello","goodbye"};

listbox.ItemsSource = strings;

strings.Remove("hello");
 

-- bryant

Blog | Twitter
_________________
Dont forget to click "Mark as Answer" on the post that helped you.

andrewjw
andrewjw

Member

Member

7 points

17 Posts

Re: Collection methods not finding Strings within collection

 Hmmm, it's interesting to see that ObservableCollection doesn't seem to suffer from the same bug... its implementation must be different.

 That's a good work-around bryant. Unfortunately for complicated reasons I can't use it, but obviously I can implement a simple work-around by writing my own custom .Contains, .IndexOf, and .Remove methods, which I can use until the bug is fixed.

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities