Reputation: 1
I am currently have a DataTable populated with data, however, I want to sort it based on two columns before using it.
Here is how my DataTable looks like
DataTable dt:
Date | Serial Number
22/06/2017 | 2
20/06/2017 | 1
22/06/2017 | 1
20/06/2017 | 2
I have research online, and tried dt.DefaultView.Sort
or LINQ
but I couldn't get it to work. I have tried these following:
dt.DefaultView.Sort = "Date, Serial Number";
DataTable newDt = dt.AsEnumerable().OrderBy(r => r.Field<DateTime>("Date"))
.ThenBy(r => r.Field<int>("Serial Number")).CopyToDataTable();
I tried both of the methods mentioned above and the result I got back was that the sorting was only based on one column, e.g:
Date | Serial Number
22/06/2017 | 2
22/06/2017 | 1
20/06/2017 | 1
20/06/2017 | 2
But that was not what I wanted. Below is what I wanted,
Expected result:
Date | Serial Number
20/06/2017 | 1
20/06/2017 | 2
22/06/2017 | 1
22/06/2017 | 2
May I know if there's any way to perform an operation to sort the DataTable in such manner? Thank you.
Upvotes: 0
Views: 925
Reputation: 66
Following code seem to work for me.
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static DataTable Dt;
static void Main(string[] args)
{
Dt = new DataTable();
Dt.Columns.Add(new DataColumn("date", typeof(DateTime)));
Dt.Columns.Add(new DataColumn("Serial Number", typeof(int)));
AddRow(Dt.NewRow(), new DateTime(2017, 06, 22), 2);
AddRow(Dt.NewRow(), new DateTime(2017, 06, 22), 1);
AddRow(Dt.NewRow(), new DateTime(2017, 06, 20), 2);
AddRow(Dt.NewRow(), new DateTime(2017, 06, 20), 1);
foreach(DataRow dr in Dt.Rows)
{
Console.WriteLine(string.Format("{0}\t{1}", dr[0], dr[1]));
}
DataView dv = Dt.DefaultView;
dv.Sort = "date, Serial Number";
foreach(DataRow dr in dv.ToTable().Rows)
{
Console.WriteLine(string.Format("{0}\t{1}", dr[0], dr[1]));
}
Console.ReadKey();
}
static void AddRow(DataRow dr, DateTime dt, int serialNumber)
{
dr[0] = dt;
dr[1] = serialNumber;
Dt.Rows.Add(dr);
}
}
}
Upvotes: 4
Reputation: 571
In LINQ you would use
XXX.OrdyBy(o => o.Field1).ThenBy(o => o.Field2)
Upvotes: 1