List.Sort based on Tag

Cheetah

Well-known member
Joined
Oct 12, 2006
Messages
232
Programming Experience
Beginner
Hi there,

I have a List of objects and I would like to sort it based on the tags of those objects.

How would i do this?

Thanks.
 
When you say "objects" and "tags" I think of the Control class and the Tag property, and "list of objects" something like List(Of T). You can then create a compare class that implements IComparer(Of T) like this:
VB.NET:
[SIZE=2][COLOR=#0000ff]Public [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Class[/COLOR][/SIZE][SIZE=2] compareTags[/SIZE]
[SIZE=2][COLOR=#0000ff]Implements[/COLOR][/SIZE][SIZE=2] IComparer([/SIZE][SIZE=2][COLOR=#0000ff]Of[/COLOR][/SIZE][SIZE=2] Control)[/SIZE]
 
[SIZE=2][COLOR=#0000ff]Public [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Function[/COLOR][/SIZE][SIZE=2] Compare([/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] x [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Windows.Forms.Control, [/SIZE][SIZE=2][COLOR=#0000ff]ByVal[/COLOR][/SIZE][SIZE=2] y [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] System.Windows.Forms.Control) [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Integer [COLOR=black]_[/COLOR][/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]Implements[/COLOR][/SIZE][SIZE=2] System.Collections.Generic.IComparer([/SIZE][SIZE=2][COLOR=#0000ff]Of[/COLOR][/SIZE][SIZE=2] System.Windows.Forms.Control).Compare[/SIZE]
[SIZE=2][COLOR=#008000]'compare x.Tag and y.Tag[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Function[/COLOR][/SIZE]
[SIZE=2][COLOR=#0000ff]End [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]Class[/COLOR][/SIZE]
With you list you can then call:
VB.NET:
[SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] l [/SIZE][SIZE=2][COLOR=#0000ff]As [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] List([/SIZE][SIZE=2][COLOR=#0000ff]Of[/COLOR][/SIZE][SIZE=2] Control)[/SIZE]
[SIZE=2][COLOR=#008000]'...[/COLOR][/SIZE]
[SIZE=2]l.Sort([/SIZE][SIZE=2][COLOR=#0000ff]New[/COLOR][/SIZE][SIZE=2] compareTags)[/SIZE]
See doc for compare value notion: http://msdn2.microsoft.com/en-us/library/xh5ks3b3.aspx
 
Ok yeah, Its a List of pictureboxes which i need to sort by the tags.

I think i get what you have already done but i dont understand the logistics of the actual sorter (the bit where you put the comment in the first of the code boxes). What would i put there if i wanted to sort by numerical order from 1 upwards?
 
Tag property is Object type, you put Integer type values there? Then you can do this:
VB.NET:
[SIZE=2][/SIZE]
[SIZE=2][COLOR=#0000ff]Return[/COLOR][/SIZE][SIZE=2] [COLOR=#0000ff]CInt[/COLOR][SIZE=2](x.Tag) [/SIZE]< [COLOR=#0000ff]CInt[/COLOR][SIZE=2](y.Tag)[/SIZE][/SIZE]
 
Where ever you like, it's Public.
 
Back
Top