Ordenar filas en una tabla de datos


Tenemos dos columnas en un DataTable, así:

COL1   COL2
Abc    5
Def    8
Ghi    3

Estamos tratando de ordenar esto datatable basado en COL2 en orden decreciente.

COL1            COL2
ghi             8
abc             4
def             3
jkl             1

Hemos intentado esto:

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

Pero, sin usar un DataView, queremos ordenar el DataTable en sí, no el DataView.

Author: Community, 2012-02-02

12 answers

Me temo que no se puede hacer fácilmente un tipo de DataTable en el lugar como suena como usted quiere hacer.

Lo que puede hacer es crear una nueva DataTable a partir de una DataView que cree a partir de su DataTable original. Aplique las clases y / o filtros que desee en la vista de datos y luego cree una nueva DataTable a partir de la vista de datos utilizando la vista de datos .ToTable método:

   DataView dv = ft.DefaultView;
   dv.Sort = "occr desc";
   DataTable sortedDT = dv.ToTable();
 296
Author: Jay Riggs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-02 06:40:06

Tal vez lo siguiente pueda ayudar:

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

Aquí, también puede usar otras consultas de expresión Lambda.

 16
Author: Vishnu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-14 01:28:07

Su Uso Simple .Seleccione la función.

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

Y está hecho......Feliz Codificación

 14
Author: Abdul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-06 11:52:46

O, si puedes usar un DataGridView, puedes llamar a 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);
        }
    }
}

Que le daría el resultado deseado:

Vista del depurador

 13
Author: Gustavo Mori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-02 06:45:26

¿Intentaste usar el método Select(filterExpression, sortOrder) en DataTable? Vea aquí para un ejemplo. Nota este método no ordenará la tabla de datos en su lugar, si eso es lo que está buscando, pero devolverá una matriz ordenada de filas sin usar una vista de datos.

 13
Author: Brian Rogers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-02 06:48:23
 table.DefaultView.Sort = "[occr] DESC";
 8
Author: ivg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-13 18:26:15

Esto te ayudará...

DataTable dt = new DataTable();         
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();
 8
Author: Ankita_systematix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 09:12:57

Resulta que hay un caso especial donde esto se puede lograr. El truco es cuando se construye la DataTable, recoger todas las filas en una lista, ordenarlos, a continuación, añadirlos. Este caso acaba de llegar aquí.

 4
Author: Joshua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-20 18:08:19

//Espero que Esto te ayude..

        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;
 4
Author: Kumod Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-09 05:54:55

Hay 2 maneras de ordenar los datos

1) ordenar solo los datos y rellenar la cuadrícula:

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) ordenar vista predeterminada que es como ordenar con encabezado de columna de cuadrícula:

DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
 3
Author: Zolfaghari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 14:21:45

TL; DR

Use tableObject.Select(queryExpression, sortOrderExpression) para seleccionar los datos de manera ordenada

Ejemplo completo

Complete ejemplo de trabajo - se puede probar en una aplicación de consola :

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

Salida

salida

 1
Author: student,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-29 11:10:59

Prueba esto:

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;
 0
Author: Rand Shaban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-23 19:44:51