如何根据条件对DataTable列进行排序

时间:2013-04-28 18:14:58

标签: c# sorting datatable calculated-columns

通过执行存储过程,我有一个动态DataTable:

A B C D

1 0 0 1

0 0 0 1

1 1 0 1

如何根据每列的总和按降序排序?我想要它:

D A B C

1 1 0 0

1 0 0 0

1 1 1 0

我创建了一个List来存储每列的总和:

List<Column> temptArray;
public class Column
{
    public int columnIndex;
    public int count;
}

我计算总和

private void calculateSum()
    {
        temptArray= new List<Column>();
        for (int column = 0; column <= dataTable.Columns.Count -1; column++)
            temptArray.Add(new Column{ columnIndex = column });

        for (int row = 0; row <= dataTable.Rows.Count - 1; row++)
            for (int column = 0; column <= dataTable.Columns.Count - 1; column++)
                temptArray[column].count+= (int)dataTable.Rows[row].ItemArray.GetValue(column);
}

它工作正常。

然后我对我的诱惑进行排序:

temptArray = temptArray.OrderByDescending(x => x.count).ToList();

我的temptArray现在应该订购:DABC

如何像temptArray一样更改DataTable顺序?

1 个答案:

答案 0 :(得分:1)

尝试使用DataColumn.SetOrdinal方法。例如:

dataTable.Columns["D"].SetOrdinal(0); 
dataTable.Columns["A"].SetOrdinal(1);
dataTable.Columns["B"].SetOrdinal(2); 
dataTable.Columns["C"].SetOrdinal(3);

以下是示例代码:

// this is sample C# console application 
using System.Data;
using System.Linq; 

namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = GetTable();
            // get list of Data Table column names like A, B, C, D...
            var columnNames = (from DataColumn col in dt.Columns
                               select col.ColumnName).ToList();
            // compute sum for each column and get list of objects which having sum and column name as property. 
            var computed = columnNames.Select(c => new { ColumnName = c, Sum = dt.Compute(string.Format("Sum({0})", c), "") }).OrderByDescending(p => p.Sum).ToList();

            // set the column position based on Sum of the column 
            for (int i = 0; i < computed.Count(); i++)
            {
                dt.Columns[computed[i].ColumnName].SetOrdinal(i);
            }

        }
        // testing I have added this method to create Data Table with testing data
        static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("A", typeof(int));
            table.Columns.Add("B", typeof(int));
            table.Columns.Add("C", typeof(int));
            table.Columns.Add("D", typeof(int));

            table.Rows.Add(1, 0, 0, 1);
            table.Rows.Add(0, 0, 0, 1);
            table.Rows.Add(1, 1, 0, 1);

            return table;
        }
    }
}