inconsistent ArrayList sort results

C

ChrisB

Hello:

I am trying to sort a collection using the sorting functionality offered by
the ArrayList but seem to be getting inconsistent results.

--------------------------------------------------------------------------------



the InvoiceLineItemCollection sort code looks like this -



internal void Sort()

{

// Sort collection items using ArrayList.

// Collection items must implement IComparable.

ArrayList arrayList = new ArrayList();



foreach(InvoiceLineItem invoiceLineItem in this)

{

arrayList.Add(invoiceLineItem.Clone());

}



arrayList.Sort();



// Repopulate collection with sorted items.

this.Clear();



foreach(Object obj in arrayList)

{

this.Add((InvoiceLineItem)obj);

}

}



----------------------------------------------------------------------------------------

The InvoiceLineItem implementation of CompareTo looks like this -

(Note: both PlanID and PlanBeneficairyID are of type GUID).



public int CompareTo(Object obj)

{

if(!(obj is InvoiceLineItem)) throw new InvalidCastException("Not an
InvoiceLineItem object.");



Int32 sortResult;



InvoiceLineItem invoiceLineItem = (InvoiceLineItem)obj;



// * Perform line Item sort. *

// Notes:

// 1. If items are equal (result = 0), comparison is based upon

// next search criteria property.

// 2. Sort criteria for line Items are:

// a. PlanID

// b. PlanBeneficiaryAssignmentID



// Compare plans(sort criteria 1).

sortResult = this.PlanID.CompareTo(invoiceLineItem.PlanID);



if(sortResult == 0)

{

// Compare plan beneficiary assignments (sort criteria 2).

sortResult =
this.PlanBeneficiaryAssignmentID.CompareTo(invoiceLineItem.PlanBeneficiaryAssignmentID);

}



return sortResult;

}



----------------------------------------------------



Any idea why the order of the items in the InvoiceLineItemCollection is not
consistent when sorting the same group of items?



Thanks!

Chris
 
C

ChrisB

Jon,

While preparing a response to your question, I realized that the Guids on
which the sort is based vary each time the related unit test runs. When
this is taken into account, the sort code appears to be working properly.

Thanks for your help.
Chris
 
J

Jon Skeet [C# MVP]

ChrisB said:
While preparing a response to your question, I realized that the Guids on
which the sort is based vary each time the related unit test runs. When
this is taken into account, the sort code appears to be working properly.

Thanks for your help.

My pleasure. It's always nice when a solution can be found and my sole
contribution is hitting Ctrl-F1 which inserts the "Could you post
a..." text for me :)
 

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

Top