5
Answers

Sort on two values

Rodney Johnson

Rodney Johnson

12y
1.4k
1
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

Answers (5)