I am trying to sort on two values and at this point am not having success. Here is a the code:
internal DataRow[] SortByCubeDecending(DataTable dr)
{
DataTable sortedDR = new DataTable();
//I am setting the data table that will be returned to the data table I am passing in to not alter the orignial
sortedDR = dr;
//This method should sort the datarow array by low weight and high cube for the nose and tail of the trailer
for (int i = 0; i < dr.Rows.Count; i++)
{
for (int j = 1; j < dr.Rows.Count; j++)
{
double cubeOne = (Convert.ToDouble(sortedDR[i][21]) *
Convert.ToDouble(sortedDR[i][22]) * Convert.ToDouble(sortedDR[i][23]));
double cubeTwo = (Convert.ToDouble(sortedDR[j][21]) *
Convert.ToDouble(sortedDR[j][22]) * Convert.ToDouble(sortedDR[j][23]));
double weightOne = Convert.ToInt16(sortedDR[i][20]) / Convert.ToInt16(sortedDR[i][19]);
double weightTwo = Convert.ToInt16(sortedDR[j][20]) / Convert.ToInt16(sortedDR[j][19]);
DataRow temp;
if (cubeOne > cubeTwo && weightOne < weightTwo && dr[i]["status"] == false && dr[j]["status"] == false)
{
temp = sortedDR[i];
sortedDR[i] = sortedDR[j];
sortedDR[j] = temp;
}
}
}
return sortedDR;
}
My goal is to return a data table sorted by cube (volume) and weight. So for example:
sortedDT[0]["cube"] = 10,000
sortedDT[0]["weight"] = 100
sortedDT[1]["cube"] = 9,000
sortedDT[1]["weight"] = 150
sortedDT[2]["cube"] = 8,500
sortedDT[2]["weight"] = 200
...
sortedDT[n - 10]["cube"] = 2,500 (I do not really care about these in the middle)
sortedDT[n - 10]["weight"] = 2,600
...
sortedDT[n]["cube"] = 1,000
sortedDT[n]["weight"] = 700
Whether I do this with a data table or DataRow[] or an array of structures makes not difference to me. What is most important at this point is I get the extreme values at either end of the sorted tables. I will most likely only be using the top, or bottom, 5 rows then resorting. The "status" column refers to whether or not this row is available. If "status" is true the row is extraneous - already acted upon.
Thank you,
Rod
Loading
VulpesPosted Dec 2, 2011, 1:03 PM
For example, if I run this simple example:
the output is :
1
2
11
and not:
1
11
2
Rodney JohnsonPosted Dec 2, 2011, 3:09 PM
Rodney JohnsonPosted Dec 2, 2011, 12:04 PM
public void SortByCubeDecending(DataRow[] dr)
{
DataTable dt = new DataTable();
dt.Columns.Add("Track");
dt.Columns.Add("Cube");
dt.Columns.Add("Weight");
for (int i = 0; i < dr.Length; i++)
{
DataRow newRow = dt.NewRow();
newRow["Track"] = dr[i][1];
newRow["Cube"] = Convert.ToDouble(dr[i][21]) * Convert.ToDouble(dr[i][22]) *
Convert.ToDouble(dr[i][23]);
newRow["Weight"] = Convert.ToDouble(dr[i][20]);
dt.Rows.Add(newRow);
}
DataView view = dt.DefaultView;
// By default, the first column sorted ascending.
view.Sort = "Cube, Weight DESC";
}
Rodney JohnsonPosted Dec 2, 2011, 11:45 AM
Regards,
VulpesPosted Dec 2, 2011, 10:52 AM
http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx