web-dev-qa-db-fra.com

Tri des lignes dans une table de données

Nous avons deux colonnes dans un DataTable, comme ceci:

COL1   COL2
Abc    5
Def    8
Ghi    3

Nous essayons de trier cette datatable sur la base de COL2 par ordre décroissant.

COL1            COL2
ghi             8
abc             4
def             3
jkl             1

Nous avons essayé ceci:

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

mais, sans utiliser un DataView, nous voulons trier le DataTable lui-même, pas le DataView.

132
vidya sagar

Je crains que vous ne puissiez pas facilement créer une sorte de DataTable sur place comme si vous le souhaitiez.

Ce que vous pouvez faire, c'est créer un nouveau DataTable à partir d'un DataView que vous avez créé à partir de votre DataTable d'origine. Appliquez les tris et/ou les filtres de votre choix sur le DataView, puis créez un nouveau DataTable à partir du DataView à l'aide de la méthode DataView.ToTable :

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

Cela vous aidera ...

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

Son utilisation simple. Sélectionnez la fonction.

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

Et c'est fait ...... Happy Coding

20
Abdul

Peut-être que ce qui suit peut aider:

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

Ici, vous pouvez également utiliser d’autres requêtes d’expression Lambda.

19
Vishnu

Avez-vous essayé d'utiliser la méthode Select(filterExpression, sortOrder) sur DataTable? Voir ici pour un exemple. Notez que cette méthode ne triera pas la table de données en place, si c'est ce que vous recherchez, mais elle retournera un tableau trié de lignes sans utiliser une vue de données.

13
Brian Rogers

Ou, si vous pouvez utiliser un DataGridView, vous pouvez simplement appeler 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);
        }
    }
}

Ce qui vous donnerait le résultat souhaité:

Debugger view

13
Gustavo Mori
 table.DefaultView.Sort = "[occr] DESC";
9
ivg

Il se trouve qu'il existe un cas particulier où cela peut être réalisé. L'astuce consiste à créer le DataTable: collectez toutes les lignes d'une liste, triez-les, puis ajoutez-les. Cette affaire vient d'arriver ici.

4
Joshua

Il y a 2 façons de trier les données

1) trier uniquement les données et les remplir dans la grille:

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) trier la vue par défaut qui ressemble à une sorte avec en-tête de colonne de grille:

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

//J'espère que cela vous aidera..

        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;
3
Kumod Singh

TL; DR

utilisez tableObject.Select(queryExpression, sortOrderExpression) pour sélectionner les données de manière triée

Exemple complet

Complet exemple de travail - peut être testé dans un application console :

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

Sortie

output

1
student

essaye ça:

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
Rand Shaban