C# 对数据表中的行进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9107916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:59:02  来源:igfitidea点击:

Sorting rows in a data table

c#sortingdatatable

提问by vidya sagar

We have two columns in a DataTable, like so:

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

COL1   COL2
Abc    5
Def    8
Ghi    3

We're trying to sort this datatablebased on COL2in decreasing order.

我们正在尝试datatable根据COL2降序对其进行排序。

COL1            COL2
ghi             8
abc             4
def             3
jkl             1

We tried this:

我们试过这个:

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

but, without using a DataView, we want to sort the DataTableitself, not the DataView.

但是,在不使用 a 的情况下DataView,我们希望对DataTable本身进行排序,而不是对DataView.

采纳答案by Jay Riggs

I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.

恐怕你不能像你想做的那样轻松地做一个就地类型的数据表。

What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTablemethod:

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

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

回答by Brian Rogers

Did you try using the Select(filterExpression, sortOrder)method on DataTable? See herefor an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.

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

回答by Gustavo Mori

Or, if you can use a DataGridView, you could just call Sort(column, direction):

或者,如果您可以使用 a 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);
        }
    }
}

Which would give you the desired result:

这会给你想要的结果:

Debugger view

调试器视图

回答by Joshua

It turns out there is a special case where this can be achieved. The trick is when building the DataTable, collect all the rows in a list, sort them, then add them. This case just came up here.

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

回答by Kumod Singh

//Hope This will help you..

//希望能帮到你..

        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;

回答by Abdul

Its Simple Use .Select function.

它的简单使用 .Select 功能。

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

And it's done......Happy Coding

大功告成……快乐编码

回答by Vishnu

Maybe the following can help:

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

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

Here, you can use other Lambda expression queries too.

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

回答by ivg

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

回答by Rand Shaban

try this:

尝试这个:

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;

回答by xameeramir

TL;DR

TL; 博士

use tableObject.Select(queryExpression, sortOrderExpression)to select data in sorted manner

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

Complete example

完整示例

Complete working example- can be tested in a 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

输出

output

输出