如何对给定列和方向的 DataTable 进行排序?

我需要在内存中求助于一个基于来自 GridView 的列和方向的 DataTable。函数应该是这样的:

public static DataTable resort(DataTable dt, string colName, string direction)
{
DataTable dtOut = null;


....
}

我需要帮助填写这个函数。我想我可以使用 Select 语句,但我不确定如何使用。我不能点击评论,因为这个浏览器,但你可以向我显示一个就地或新的 DataTable 解决方案,任何一个。对于那些向我展示指针的人,我需要一个类似于原型的编码函数。

这个怎么样:

// ds.Tables[0].DefaultView.Sort="au_fname DESC";
public static void Resort(ref DataTable dt, string colName, string direction)
{
string sortExpression = string.Format("{0} {1}", colName, direction);
dt.DefaultView.Sort = sortExpression;
}
214706 次浏览

Create a DataView. You cannot sort a DataTable directly, but you can create a DataView from the DataTable and sort that.

Creating: http://msdn.microsoft.com/en-us/library/hy5b8exc.aspx

Sorting: http://msdn.microsoft.com/en-us/library/13wb36xf.aspx

The following code example creates a view that shows all the products where the number of units in stock is less than or equal to the reorder level, sorted first by supplier ID and then by product name.

DataView prodView = new DataView(prodDS.Tables["Products"], "UnitsInStock <= ReorderLevel", "SupplierID, ProductName", DataViewRowState.CurrentRows);

DataTables have an overloaded Select method that you can you to do this. See here: http://msdn.microsoft.com/en-us/library/way3dy9w.aspx

But the return val of the Select call is not a DataTable but an array of RowData objects. If you want to return a DataTable from your function you will have to build it from scratch based on that data array. Here is a post that addresses and provides a sample for both issues: http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/157a4a0f-1324-4301-9725-3def95de2bf2/

If you've only got one DataView, you can sort using that instead:

table.DefaultView.Sort = "columnName asc";

Haven't tried it, but I guess you can do this with any number of DataViews, as long as you reference the right one.

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
DataTable dtOut = null;
dt.DefaultView.Sort = colName + " " + direction;
dtOut = dt.DefaultView.ToTable();
return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}

Actually got the same problem. For me worked this easy way:

Adding the data to a Datatable and sort it:

dt.DefaultView.Sort = "columnname";
dt = dt.DefaultView.ToTable();

In case you want to sort in more than one direction

  public static void sortOutputTable(ref DataTable output)
{
DataView dv = output.DefaultView;
dv.Sort = "specialCode ASC, otherCode DESC";
DataTable sortedDT = dv.ToTable();
output = sortedDT;
}