Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort an array by 2 different fields one after the other 2

Status
Not open for further replies.

UCFSteve

Programmer
Apr 14, 2005
11
US
I need to sort an array that contains multiple objects. I need to first sort it by Rank, then by Last name.

Ex
Array[0].rank = 3 Array[0].name = Jones
Array[1].rank = 2 Array[1].name = Adams
Array[2].rank = 3 Array[2].name = Scott
Array[3].rank = 1 Array[3].name = Murphy
Array[4].rank = 3 Array[4].name = Daley

such that the output array is like this:

Array[0].rank = 1 Array[0].name = Murphy
Array[1].rank = 2 Array[1].name = Adams
Array[2].rank = 3 Array[2].name = Daley
Array[3].rank = 3 Array[3].name = Jones
Array[4].rank = 3 Array[4].name = Scott

I have attempted to create my own comparer class inheriting icompare but it doesnt seem to allow me to sort on 2 items at the same time. I can either sort on name or rank but if I sort on name before I sort on rank the items show up like this:

Array[0].rank = 1 Array[0].name = Murphy
Array[1].rank = 2 Array[1].name = Adams
Array[2].rank = 3 Array[2].name = Jones
Array[3].rank = 3 Array[3].name = Daley
Array[4].rank = 3 Array[4].name = Scott



Any help would be appreciated. thanks,
 
1)I think the probplem is in the compare function.
2)I would reverse that array into a DataTable (the columns will be rank and name) and a row is an object of the array. With dat you can sort on as many columns you want, even more , you can filter the objects ( e.g. sort only those objects for which rank is between 10 and 100 , or compute a new column as expression.
Code:
DataTable dt = new DataTable();
DataColumn col1=new DataColumn("rank");
dt.Columns.Add(col1);
DataColumn col2 = new DataColumn("name");
DataRow dr=null;
for (int i=0;i<arr.Length;i++)
{
   dr = dt.NewRow();
   dt.Rows.Add(dr);
   dr["rank"]=arr[i].rank;
   dr["name"]=arr[i].name;
}
DataView dv=dt.DefaultView;
dv.Sort("rank DESC, name ASC");// DESC by rank and ASC by name
If you reaplce the array by DataTable you will need only the last two statements.
obislavu

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top