[Reprint] C# uses DataTable to do paging query | Filter the content of the DataTable table according to the field

using System.Data;

namespace Demo.Code
{
    public static class ExtTable
    {
        /// <summary>
        /// Get the data of a page in the table
        /// </summary>
        /// <param name="data">Table data</param>
        /// <param name="pageIndex">Current page</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="allPage">returns the total number of pages</param>
        /// <returns>Return the current page table data</returns>
        public static DataTable GetPage(this DataTable data, int pageIndex, int pageSize, out int allPage)
        {
            allPage = data.Rows.Count / pageSize;
            allPage += data.Rows.Count % pageSize == 0 ? 0 : 1;
            DataTable Ntable = data.Clone();
            int startIndex = pageIndex * pageSize;
            int endIndex = startIndex + pageSize > data.Rows.Count ? data.Rows.Count : startIndex + pageSize;
            if (startIndex < endIndex)
                for (int i = startIndex; i < endIndex; i++)
                {
                    Ntable.ImportRow(data.Rows[i]);
                }
            return Ntable;
        }
        /// <summary>
        /// Filter the contents of the table according to the field
        /// </summary>
        /// <param name="data">Table data</param>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        ///
        public static DataTable GetDataFilter(DataTable data, string condition)
        {
            if (data != null && data.Rows.Count > 0)
            {
                if (condition.Trim() == "")
                {
                    return data;
                }
                else
                {
                    DataTable newdt = new DataTable();
                    newdt = data.Clone();
                    DataRow[] dr = data.Select(condition);//如:Select("id=123");Select("name='Tom'");Select("columnname1 like '%xx%'");
                    for (int i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)dr[i]);
                    }
                    return newdt;
                }
            }
            else
            {
                return null;
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484066&siteId=291194637