变相实现DataView Top *** 功能

今天一个同事问我Datatable中怎么实现SQL中的 Top功能,我想当然的说用 DataView的筛选中能(rowfilter方法),但自己试验了一下发现不能直接调用,呵呵只好间接实现,既然rowfilter是封装的SQL语句的Where子句那就从这里入手
 /// <summary></summary>
    /// Gets the latest comments.
    /// 
    /// The comments.
    /// The num comments.
    /// The sort id.
    /// <returns></returns>
    public static DataView GetTopComments(DataView Comments,int numComments,string sortId)
    {
        string filter = string.Empty;
        string delimiter = string.Empty;
        numComments = Math.Min(numComments, Comments.Count);

        for (int i = 0; i < numComments; i++)
        {
            filter += delimiter + Comments[i][sortId].ToString();
            delimiter = ",";
        }

        if (filter.Length > 0)
        {
            Comments.RowFilter = sortId+" in (" + filter + ")";
        }

        return Comments;
    }
调用:
DataTable dt = GetTable(); DataView dv = dt.DefaultView; DataTable newDt = GetTopComments(dv, 18).Table;

你可能感兴趣的:(sql)