English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Hi everyone,

I have an arraylist which gets populated from a database with two properties: NAME and AGE. How can I sort the arraylist by age, then by name? If I have:
maria 24
jason 30
andy 24
I need it to be sorted by age first, and then by name, so I should get the following result:
andy 24
maria 24
jason 30
(notice andy/maria alphabetically sorted).
I have tried to sort it by a property at a time, but if I do that by the time I've done the second sorting the first one is lost. I kinda need it to act like an SQL-Like ORDER BY, which won't work for me since I need to sort it after the arraylist is populated. Please let me know if you know how I can do that.

Thank you in advance

2006-06-21 06:49:28 · 4 answers · asked by Dookie 3 in Computers & Internet Programming & Design

4 answers

In the class you are using to store each person, implement the IComparable interface. You will write your own version of CompareTo() that ArrayList.Sort() will use to sort your objects. Here's a link to MSDNs section on IComparable.

http://msdn2.microsoft.com/en-us/system.icomparable.compareto(VS.80).aspx

2006-06-21 07:12:58 · answer #1 · answered by Anonymous · 0 0

Vb.net Arraylist Sort

2016-12-12 10:04:04 · answer #2 · answered by ? 4 · 0 0

While there are a lot of sort algorhythms out there on the Internet, I'd really suggest to you that you change your approach altogether. Don't use an ArrayList object. Put everything into a DataTable, then call its DataView. Sort algorythms will be slower and less powerful than the hidden xpath queries happening behind the scenes in a DataView, especially since you're talking about a recursive sort.

Dim Fred as new DataTable("MyTable")
Fred.Columns.Add("FirstName")
Fred.Columns.Add("Age",_
System.Type.GetType("System.Integer")
Dim dr as DataRow = dt.NewRow()
dr("Name") = "Wilma"
dr("Age") = 23
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("Name") = "Bob"
dr("Age") = 22
dt.Rows.Add(dr)

DataView dv = dt.DefaultView
dv.Sort = "Name ASC, Age ASC"

DataGrid1.DataSource = dv
DataGrid1.DataBind()

2006-06-21 08:06:53 · answer #3 · answered by evolver 6 · 0 0

tricky aspect. look into with google. it will help!

2014-11-06 16:13:00 · answer #4 · answered by Anonymous · 0 0

fedest.com, questions and answers