Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - DataTable column reorder

I'm using a DataTable with the contents

       column1    column2   column3  column4 column5 column6 column7 column8 column9 column10
row1   a           b         c         d       e       f       g      h       i        j

I want the table to be reorderd as

        column4    column2    column1  column7 column6 column9 column10 column5 column8 column3
row1     d         b           a         g      f       i       j        e       h       c    

I tried using the DataTable.Column[i].SetOrdinal() method but it swaps only the first column properly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you haven't shown the full code it's difficult to say what's actually wrong. But this should work:

public static void ReorderTable(ref DataTable table, params String[] columns)
{
    if (columns.Length != table.Columns.Count)
        throw new ArgumentException("Count of columns must be equal to table.Column.Count", "columns");

    for (int i = 0; i < columns.Length; i++)
    {
        table.Columns[columns[i]].SetOrdinal(i);
    }
}

Instead of a params String[] you could also use a List<DataColumn> or whatelse you prefer.

Tested with your sample data:

var table = new DataTable();
table.Columns.Add("column1", typeof(string));
table.Columns.Add("column2", typeof(string));
table.Columns.Add("column3", typeof(string));
table.Columns.Add("column4", typeof(string));
table.Columns.Add("column5", typeof(string));
table.Columns.Add("column6", typeof(string));
table.Columns.Add("column7", typeof(string));
table.Columns.Add("column8", typeof(string));
table.Columns.Add("column9", typeof(string));
table.Columns.Add("column10", typeof(string));

for (int i = 0; i < 10; i++)
{
    table.Rows.Add("colum1", "column2", "colum3", "column4", "column5", "column6", "column7", "column8", "column9", "column10");
}

ReorderTable(ref table, "column4", "column2", "column1", "column7", "column6", "column9", "column10", "column5", "column8", "column3");

Works already with .NET 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...