C implements the Datatable sorting method

  • 2020-10-23 21:11:33
  • OfStack

This article shows how C# implements Datatable sorting and shares it with you for your reference. The specific methods are as follows:

In general, to sort Datatable in C#, use the Sort method of DefaultView. You need to get the DefaultView of Datatable, then set the sort property of the resulting Dataview, and finally export the sorted dataview to Datatable using the view's ToTable method.

The code is as follows:


DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 12, "lwolf" });
dt.Rows.Add(new object[] { 100,"kkkkk"});
dt.Rows.Add(new object[] { 19,"jim" });
dt.Rows.Add(new object[] { 1,"test" });
DataTable dtCopy = dt.Copy();
DataView dv = dt.DefaultView;
dv.Sort = "ID";
dtCopy = dv.ToTable();

So you end up with Datable sorted.

Hopefully this article has helped you with your C# programming.


Related articles: