Comparing arraylist

  • Thread starter Thread starter Robert Linder
  • Start date Start date
R

Robert Linder

I am trying to compare arraylists in csharp.

I setup a simple test with empty arraylists.

string [] x1 = {};
string [] x2 = {};
Console.WriteLine( x1 == x2 ); // false
Console.WriteLine( x1.Equals(x2) ); // false
Console.WriteLine( x1.GetLength(0) == 0 ); // true

What is the way to compare arraylist?

What is the way to check for empty arraylist?
GetLength is bad when there is a large arraylist.

This works, but I prefer something like 'x1.IsEmpty()'
try{Console.WriteLine( x1.GetValue(0) );}
catch( System.IndexOutOfRangeException )
{Console.WriteLine( "Empty Arraylist"); }

Robert
 
Robert Linder said:
What is the way to compare arraylist?

I think you need to iterate over the elements and compare them individually.
What is the way to check for empty arraylist?

if (ArrayList.Count == 0) { /* it is empty */ }

P.
 
x1.Length == 0 will do it.

This is always very fast, even if the array is large, because the length is
stored. It is not recomputed every time.

Also, string[] is an "array", not an "ArrayList". And arrays have
"reference" semantics. So, x1 == x2 and x1.Equals(x2) will compare the
references rather than the contents of the two arrays, and will return false
in your case, unless you assign x2 to x1 (x1 = x2;).

Bruno.
 
Back
Top