searching multi - Item arraylist

  • Thread starter Thread starter Jon Paal
  • Start date Start date
J

Jon Paal

how can I search for a value in a multi - item arraylist to prevent adding duplicates ?
 
Hey Jon,

To prevent dups i'll use the Contains Method of the Arraylist like

if(!myArrayList.Contains(obj))
{
myArrayList.Add(obj);
}

Hope thats what u were looking for,
T
 
it's not working for me . I add a new item as multi-dimensional like this:

"arrChartList.Add( New ChartItem (Unit,Amount ) ) "


How do I test for existence of ChartItem ?

I tried but no success with :

If Not arrChartList.Contains(ChartItem ( Unit,Amount ) ) Then
arrChartList.Add( New ChartItem (Unit,Amount ) )
End If
 
Hi,

Jon said:
it's not working for me . I add a new item as multi-dimensional like this:

"arrChartList.Add( New ChartItem (Unit,Amount ) ) "


How do I test for existence of ChartItem ?

I tried but no success with :

If Not arrChartList.Contains(ChartItem ( Unit,Amount ) ) Then
arrChartList.Add( New ChartItem (Unit,Amount ) )
End If

When you use the "Contains" method to look an item up, the item you pass
to the Contains method must be a reference to the *same* object stored
in the ArrayList. In other words, the '==' operator must return true.
For a string, you can use a different object with the same value,
because the '==' operator works this way for strings. But for an object,
it doesnt' work.

MyObject obj1 = new MyObject( 3, 4, 5 );
MyObject obj2 = new MyObject( 3, 4, 5 );
obj1 == obj2; // this is false, unless you override the '==' operator to
return a different value.

So... to solve your problem, there are different ways. One is to save a
reference to the ChartItem you create somewhere in your code, and to use
this reference to check if it was added to the ArrayList already, or you
can use a Hashtable and check for the Key rather than for the value
itself. Since the key can be pretty much anything, you can use for
example a string representation of your ChartItem, which makes things
easier.

HTH,
Laurent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top