如何对给定列和方向的 DataTable 进行排序? [英] How do you Sort a DataTable given column and direction?

查看:37
本文介绍了如何对给定列和方向的 DataTable 进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在内存中使用基于来自 GridView 的列和方向的 DataTable.该函数需要如下所示:

I need to resort, in memory, a DataTable based on a column and direction that are coming from a GridView. The function needs to look like this:

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

    ....
}

我需要帮助填写此功能.我想我可以使用 Select 语句,但我不确定如何.由于此浏览器,我无法单击评论",但您可以向我展示就地或新的 DataTable 解决方案,任一种.请给我指点的人,我需要一个类似于原型的编码函数.

I need help filling in this function. I think I can use a Select statement but I am not sure how. I can't click on Comments because of this browser but you can show me an in-place or new DataTable solution, either one. For the people showing me pointers, please, I need a coded function similar to the one prototyped.

怎么样:

// 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;
   }

推荐答案

我假设direction"是ASC"或DESC"并且dt包含一个名为colName"的列

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

或不创建 dtOut

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

这篇关于如何对给定列和方向的 DataTable 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆