简体   繁体   English

对数据表中的行进行排序

[英]Sorting rows in a data table

We have two columns in a DataTable , like so:我们在DataTable有两列,如下所示:

COL1   COL2
Abc    5
Def    8
Ghi    3

We're trying to sort this datatable based on COL2 in 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 DataTable itself, not the DataView .但是,在不使用DataView ,我们希望对DataTable本身进行排序,而不是对DataView进行排序。

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.您可以做的是从您从原始 DataTable 创建的 DataView 创建一个新的 DataTable。 Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:在 DataView 上应用您想要的任何排序和/或过滤器,然后使用DataView.ToTable方法从 DataView 创建一个新的 DataTable:

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

This will help you...这将帮助你...

DataTable dt = new DataTable();         
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();

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大功告成……快乐编码

Maybe the following can help:也许以下内容可以提供帮助:

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

Here, you can use other Lambda expression queries too.在这里,您也可以使用其他 Lambda 表达式查询。

Did you try using the Select(filterExpression, sortOrder) method on DataTable?您是否尝试在 DataTable 上使用Select(filterExpression, sortOrder)方法? See here for 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.请注意,此方法不会对数据表进行原地排序,如果这是您要查找的内容,但它会在不使用数据视图的情况下返回已排序的行数组。

Or, if you can use a DataGridView , you could just call Sort(column, direction) :或者,如果您可以使用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:这会给你想要的结果:

调试器视图

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

Use LINQ - The beauty of C#使用 LINQ - C# 之美

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

There is 2 way for sort data排序数据有两种方式

1) sorting just data and fill into grid: 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) sort default view that is like of sort with grid column header: 2)排序默认视图,类似于带有网格列标题的排序:

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

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.诀窍是在构建 DataTable 时,收集列表中的所有行,对它们进行排序,然后添加它们。 This case just came up here.这个案例刚刚出现在这里。

//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;

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 aconsole 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输出

输出

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;

Yes the above answers describing the corect way to sort datatable是的,上面的答案描述了对数据表进行排序的正确方式

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

But in addition to this, to select particular row in it you can use LINQ and try following但除此之外,要选择其中的特定行,您可以使用 LINQ 并尝试以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM