DataTable去重

Posted Cein

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataTable去重相关的知识,希望对你有一定的参考价值。

  #region datatable去重
        /// <summary>
        /// datatable去重
        /// </summary>
        /// <param name="dtSource">需要去重的datatable</param>
        /// <param name="columnNames">依据哪些列去重</param>
        /// <returns></returns>
        public static DataTable GetDistinctTable(DataTable dtSource, params string[] columnNames)
        {
            DataTable distinctTable = dtSource.Clone();
            try
            {
                if (dtSource != null && dtSource.Rows.Count > 0)
                {
                    DataView dv = new DataView(dtSource);
                    distinctTable = dv.ToTable(true, columnNames);
                }
            }
            catch (Exception ee)
            {
            }
            return distinctTable;
        }

        /// <summary>
        /// datatable去重
        /// </summary>
        /// <param name="dtSource">需要去重的datatable</param>
        /// <returns></returns>
        public static DataTable GetDistinctTable(DataTable dtSource)
        {
            DataTable distinctTable = null;
            try
            {
                if (dtSource != null && dtSource.Rows.Count > 0)
                {
                    string[] columnNames = GetTableColumnName(dtSource);
                    DataView dv = new DataView(dtSource);
                    distinctTable = dv.ToTable(true, columnNames);
                }
            }
            catch (Exception ee)
            {
            }
            return distinctTable;
        }

        #endregion

        #region 获取表中所有列名
        public static string[] GetTableColumnName(DataTable dt)
        {
            string cols = string.Empty;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                cols += (dt.Columns[i].ColumnName + ",");
            }
            cols = cols.TrimEnd(,);
            return cols.Split(,);
        }
        #endregion

 

以上是关于DataTable去重的主要内容,如果未能解决你的问题,请参考以下文章

20180322 对DataTable里面的数据进行去重

datatable去重

linq查询DataTable中的某列去重数据

DataTable中数据针对某列数据去重

去除DataTable指定列的重复行

Linq去重(自定义字段)