3月 22

因为经常要对List<T>或者DataTable进行分组,所以就封装了一下
其实也没有什么,主要是DataTable要用ImportRow方法

     public class OtherManager<T>
    {
        /// <summary>
        /// 对List进行分片
        /// </summary>
        /// <param name="source">要分片的List<T></param>
        /// <param name="pageSize">分片的页容积</param>
        /// <returns></returns>
        public static List<List<T>> Segement(List<T> source, int pageSize)
        {
            List<List<T>> list = new List<List<T>>();

            if (source == null || source.Count == 0)
            {
                return list;
            }

            int totalRec = source.Count;

            int totalPage = totalRec % pageSize == 0 ? totalRec / pageSize : totalRec / pageSize + 1;
          
            for (int index = 0; index < totalPage; index++)
            {
                int start = index * pageSize;
                List<T> tmp = new List<T>();
                if (index == totalPage - 1)//最后一页,半页
                {
                    for (int row = start; row < totalRec; row++)
                    {
                        tmp.Add(source[row]);
                    }
                }
                else//满页
                {
                    for (int row = start; row < start + pageSize; row++)
                    {
                        tmp.Add(source[row]);
                    }
                }
                list.Add(tmp);
            }
            return list;
        }


        /// <summary>
        /// 对DataTable进行分片
        /// </summary>
        /// <param name="source">要分片的DataTable</param>
        /// <param name="pageSize">分片的页容积</param>
        /// <returns></returns>
        public static List<DataTable> Segement(DataTable source, int pageSize)
        {
            List<DataTable> list = new List<DataTable>();
            if (source == null || source.Rows.Count == 0)
            {
                return list;
            }

            int totalRec = source.Rows.Count;

            int totalPage = totalRec % pageSize == 0 ? totalRec / pageSize : totalRec / pageSize + 1;
          
            for (int index = 0; index < totalPage; index++)
            {
                int start = index * pageSize;
                DataTable dt = new DataTable();

                if (index == totalPage - 1)//最后一页,半页
                {
                    for (int row = start; row < totalRec; row++)
                    {
                        dt.ImportRow(source.Rows[row]);
                    }
                }
                else//满页
                {
                    for (int row = start; row < start + pageSize; row++)
                    {
                        dt.ImportRow(source.Rows[row]);
                    }
                }
                list.Add(dt);
            }
            return list;
        }

    }

written by ocean