DataTable 列重新排序

DataTable column reorder(DataTable 列重新排序)
本文介绍了DataTable 列重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有内容的 DataTable

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    

我尝试使用 DataTable.Column[i].SetOrdinal() 方法,但它只正确交换第一列.

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

推荐答案

由于您没有显示完整的代码,因此很难说到底出了什么问题.但这应该可行:

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);
    }
}

你也可以使用 List<DataColumn> 或其他你喜欢的东西来代替 params String[].

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");

已经在 .NET 2 中工作了.

Works already with .NET 2.

这篇关于DataTable 列重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)