Sorting rows in a data table
C#SortingDatatableC# Problem Overview
We have two columns in a DataTable
, like so:
COL1 COL2
Abc 5
Def 8
Ghi 3
We're trying to sort this datatable
based on COL2
in decreasing order.
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
.
C# Solutions
Solution 1 - C#
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.ToTable method:
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
Solution 2 - C#
This will help you...
DataTable dt = new DataTable();
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();
Solution 3 - C#
Its Simple Use .Select function.
DataRow[] foundRows=table.Select("Date = '1/31/1979' or OrderID = 2", "CompanyName ASC");
DataTable dt = foundRows.CopyToDataTable();
And it's done......Happy Coding
Solution 4 - C#
Maybe the following can help:
DataRow[] dataRows = table.Select().OrderBy(u => u["EmailId"]).ToArray();
Here, you can use other Lambda expression queries too.
Solution 5 - C#
Did you try using the Select(filterExpression, sortOrder)
method on DataTable? 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.
Solution 6 - C#
Or, if you can use a DataGridView
, you could just call 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:
Solution 7 - C#
table.DefaultView.Sort = "[occr] DESC";
Solution 8 - C#
Use LINQ - The beauty of C#
DataTable newDataTable = baseTable.AsEnumerable()
.OrderBy(r=> r.Field<int>("ColumnName"))
.CopyToDataTable();
Solution 9 - C#
There is 2 way for sort data
-
sorting just data and fill into grid:
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;
-
sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data DataTable dt1 = new DataTable(); // have data dt1.DefaultView.Sort = "ID DESC"; datagridview1.DataSource = dt1;
Solution 10 - C#
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.
Solution 11 - C#
//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;
Solution 12 - C#
#TL;DR
use tableObject.Select(queryExpression, sortOrderExpression)
to select data in sorted manner
#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
Solution 13 - C#
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;
Solution 14 - C#
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
var Temp = MyDataSet.Tables[0].AsEnumerable().Take(1).CopyToDataTable();