0

I am struggling with some algorithm to handle re-ordering of a C# data table based on a a column value.

So, datatable, among other columns, has a RANK column. Through GUI, user can change the rank and I need to be able to re-order that data table based on rank.

The method I am using that is supposed to update the data table has an object parameter that contains the updated row's data, including new and old rank as well as unmodified data table content.

For instance, if initial table looks like below, with first column being rank:

1  A
2  B
3  C
4  D
5  E

and I change the rank of 3rd row from 3 to 5, it should look like

1  A
2  B
3  D
4  E
5  C

Or, if I change rank of 3rd row from 3 to 2, it would become:

1  A
2  C
3  B
4  D
5  E

I did not include anything I tried because none of them worked.

1 Answer 1

0

This seems to have worked for me. What I had to work with was a data table containing unmodified data and one object that had the content of the row being modified, including its rank. This object, among other things, has the old rank and the new rank.

So, first thing, since I already have the modified row's content in an object was to delete that row from the data table. Then called the following method, passing updated data table (with the edited row removed), updated row's old and new rank.

This method returns the data table with proper ranking, after which I just add the edited row to it.

private static DataTable ReorderDataTable(DataTable dtRules, int iNewRank, int iOldRank)
{
    DataTable dtOut = dtRules.Copy();
    dtOut.DefaultView.Sort = "RANK ASC";
    dtOut = dtOut.DefaultView.ToTable();

    if (iOldRank < iNewRank)    // rule moved down in rank (e.g., 2 to 4)
    { 
        for (int i = iOldRank - 1; i < iNewRank - 1; i++)
        {
            dtOut.Rows[i]["RANK"] = Convert.ToInt16(dtOut.Rows[i]["RANK"]) - 1;
        }
    }
    else    // rule moved up in rank (e.g., 4 to 2)
    {
        for (int i = iNewRank - 1; i < iOldRank - 1; i++)
        {
            dtOut.Rows[i]["RANK"] = Convert.ToInt16(dtOut.Rows[i]["RANK"]) + 1;
        }
    }
    return dtOut;
}

I am sure there are more efficient and elegant ways to do this and it would be nice if someone could post a better solution.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.