对数据表中的行进行排序

时间:2012-02-02 06:12:42

标签: c# sorting datatable

我们在DataTable中有两列,如下所示:

COL1   COL2
Abc    5
Def    8
Ghi    3

我们正在尝试按递减顺序对datatable COL2进行排序。

COL1            COL2
ghi             8
abc             4
def             3
jkl             1

我们尝试了这个:

ft.DefaultView.Sort = "occr desc";
ft = ft.DefaultView.ToTable(true);

但是,如果不使用DataView,我们希望对DataTable本身进行排序,而不是DataView

14 个答案:

答案 0 :(得分:320)

我担心你不能像你想要的那样轻松地进行就地排序的DataTable。

您可以做的是从您从原始DataTable创建的DataView创建一个新的DataTable。在DataView上应用您想要的任何排序和/或过滤器,然后使用DataView.ToTable方法从DataView创建新的DataTable:

   DataView dv = ft.DefaultView;
   dv.Sort = "occr desc";
   DataTable sortedDT = dv.ToTable();

答案 1 :(得分:22)

这会对你有帮助......

$ ./bin/start-all.sh

答案 2 :(得分:19)

简单使用。选择功能。

DataRow[] foundRows=table.Select("Date = '1/31/1979' or OrderID = 2", "CompanyName ASC");
DataTable dt = foundRows.CopyToDataTable();

它完成了......快乐编码

答案 3 :(得分:19)

也许以下内容可以提供帮助:

DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();

在这里,您也可以使用其他Lambda表达式查询。

答案 4 :(得分:13)

您是否尝试在DataTable上使用Select(filterExpression, sortOrder)方法?有关示例,请参阅here。请注意,此方法不会对数据表进行排序,如果这是您要查找的内容,但它将返回已排序的行数组,而不使用数据视图。

答案 5 :(得分:13)

或者,如果您可以使用DataGridView,则可以致电Sort(column, direction)

namespace Sorter
{
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Add("Abc", 5);
            this.dataGridView1.Rows.Add("Def", 8);
            this.dataGridView1.Rows.Add("Ghi", 3);
            this.dataGridView1.Sort(this.dataGridView1.Columns[1], 
                                    ListSortDirection.Ascending);
        }
    }
}

哪会给你想要的结果:

Debugger view

答案 6 :(得分:9)

 table.DefaultView.Sort = "[occr] DESC";

答案 7 :(得分:4)

事实证明,有一种特殊情况可以实现。诀窍在于构建DataTable时,收集列表中的所有行,对它们进行排序,然后添加它们。这个案子刚来到这里。

答案 8 :(得分:3)

//希望这会对你有帮助..

        DataTable table = new DataTable();
        //DataRow[] rowArray = dataTable.Select();
        table = dataTable.Clone();
        for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
        {
            table.ImportRow(dataTable.Rows[i]);
        }
        return table;

答案 9 :(得分:3)

排序数据有两种方法

1)只对数据进行排序并填入网格:

DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
    dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;

2)排序默认视图,类似于带有网格列标题的排序:

DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;

答案 10 :(得分:1)

TL; DR

使用tableObject.Select(queryExpression, sortOrderExpression)以排序方式选择数据

完整示例

完成working example - 可以在console application中进行测试:

    using System;
    using System.Data;

    namespace A
    {
        class Program
        {
            static void Main(string[] args)
            {
                DataTable table = new DataTable("Orders");
                table.Columns.Add("OrderID", typeof(Int32));
                table.Columns.Add("OrderQuantity", typeof(Int32));
                table.Columns.Add("CompanyName", typeof(string));
                table.Columns.Add("Date", typeof(DateTime));

                DataRow newRow = table.NewRow();
                newRow["OrderID"] = 1;
                newRow["OrderQuantity"] = 3;
                newRow["CompanyName"] = "NewCompanyName";
                newRow["Date"] = "1979, 1, 31";

                // Add the row to the rows collection.
                table.Rows.Add(newRow);

                DataRow newRow2 = table.NewRow();
                newRow2["OrderID"] = 2;
                newRow2["OrderQuantity"] = 2;
                newRow2["CompanyName"] = "NewCompanyName1";
                table.Rows.Add(newRow2);

                DataRow newRow3 = table.NewRow();
                newRow3["OrderID"] = 3;
                newRow3["OrderQuantity"] = 2;
                newRow3["CompanyName"] = "NewCompanyName2";
                table.Rows.Add(newRow3);

                DataRow[] foundRows;

                Console.WriteLine("Original table's CompanyNames");
                Console.WriteLine("************************************");
                foundRows = table.Select();

                // Print column 0 of each returned row.
                for (int i = 0; i < foundRows.Length; i++)
                    Console.WriteLine(foundRows[i][2]);

                // Presuming the DataTable has a column named Date.
                string expression = "Date = '1/31/1979' or OrderID = 2";
                // string expression = "OrderQuantity = 2 and OrderID = 2";

                // Sort descending by column named CompanyName.
                string sortOrder = "CompanyName ASC";

                Console.WriteLine("\nCompanyNames data for Date = '1/31/1979' or OrderID = 2, sorted CompanyName ASC");
                Console.WriteLine("************************************");
                // Use the Select method to find all rows matching the filter.
                foundRows = table.Select(expression, sortOrder);

                // Print column 0 of each returned row.
                for (int i = 0; i < foundRows.Length; i++)
                    Console.WriteLine(foundRows[i][2]);

                Console.ReadKey();
            }
        }
    }

输出

output

答案 11 :(得分:1)

使用LINQ-C#的美丽

DataTable newDataTable = baseTable.AsEnumerable()
                   .OrderBy(r=> r.Field<int>("ColumnName"))
                   .CopyToDataTable();

答案 12 :(得分:0)

试试这个:

DataTable DT = new DataTable();
DataTable sortedDT = DT;
sortedDT.Clear();
foreach (DataRow row in DT.Select("", "DiffTotal desc"))
{
    sortedDT.NewRow();
    sortedDT.Rows.Add(row);
}
DT = sortedDT;

答案 13 :(得分:0)

是的,上面的答案描述了对数据表进行排序的正确方法

DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();

但除此之外,要选择其中的特定行,您可以使用 LINQ 并尝试以下操作

var Temp = MyDataSet.Tables[0].AsEnumerable().Take(1).CopyToDataTable();
相关问题