tags:

views:

443

answers:

4

Hi all,

I have a slightly odd problem that I think is most likely due to an act of foolishness on my part, but for the life of me I (and other members of my team) can't see it.

I have an object that contains a generic list property which I would like to sort. I have written a comparer class to do this for me and I am calling it in the following way:

baseObject.ListOfThings.Sort(new ThingComparer())

I have debugged into my compare function and it is returning the right values.

However After the sort call, the list remains unchanged. Have I missed something obvious, or is there something else I need to do.

Many thanks

EDIT: Yes I was being a fool, and the property returning a list was recreating it from scratch each time it was accessed. Thank you for your help everyone, and I will try to learn to check things better before asking for help in future

A: 

Looks perfectly fine to me. Is the ListOfThings property returning a copy of the underlying list perhaps?

Then you would be sorting a copy of the list which is then lost and you are given a new copy of the list in the original order the next time ListOfThings is called.

Garry Shutler
+1  A: 

Is your base object recreating the list every time its accessed? Every time someone has asked me to help with this issue, that has turned out to be the problem. Maybe the property is calling a database, building the list when its accessed, etc...

Scott Ivey
A: 

I don't know the rest of the code, but what about trying something like this :

baseObject.ListOfThings.Sort(AddressOf ThingComparer)

(assuming you got Shared Function to call)

dr. evil
A: 

To understand what's going on here, we need some more context into how ListOfThings is implemented. In particular we need to know

  • Is it a Property. If so please show us the Get Method
  • What is the type of ListOfThings

It appears to be a property and there are numereous ways this could be implemented in such a way that would cause this behavior. For instance the following definition would cause the exact behavior you are seeing

Public ReadOnly Property ListOfThings As List(Of Thing) 
  Get
    Return New List(Of Thing)(someInternalList)
  End Get
End Property
JaredPar