• C# DataTable去重,根据列名去重保留其他列


    //去掉重复行
    DataView dv = table.DefaultView;
    table = dv.ToTable(true, new string[] { "name", "code" });
    
    此时table 就只有name、code无重复的两行了,如果还需要id值则
    
    table = dv.ToTable(true, new string[] { "id","name", "code" });//第一个参数true 启用去重复,类似distinct 

    如果有一组数据(id不是唯一字段)

    通过上面的方法得到

    去重复去掉的仅仅是 id name code完全重复的行,如果想要筛选的数据仅仅是name不允许重复呢?

    table = dv.ToTable(true, new string[] { "name"});

    得到:

    但是我想要的结果是只针对其中的一列name列 去重复,还要显示其他的列

    需要的结果是:

    该怎么实现?下面的方法就可以,也许有更好的方法,

    #region 删除DataTable重复列,类似distinct
            /// <summary>   
            /// 删除DataTable重复列,类似distinct   
            /// </summary>   
            /// <param name="dt">DataTable</param>   
            /// <param name="Field">字段名</param>   
            /// <returns></returns>   
            public static DataTable DeleteSameRow(DataTable dt, string Field)
            {
                ArrayList indexList = new ArrayList();
                // 找出待删除的行索引   
                for (int i = 0; i < dt.Rows.Count - 1; i++)
                {
                    if (!IsContain(indexList, i))
                    {
                        for (int j = i + 1; j < dt.Rows.Count; j++)
                        {
                            if (dt.Rows[i][Field].ToString() == dt.Rows[j][Field].ToString())
                            {
                                indexList.Add(j);
                            }
                        }
                    }
                }
                indexList.Sort();
     // 排序
                for (int i = indexList.Count - 1; i >= 0; i--)// 根据待删除索引列表删除行  
                {
                    int index = Convert.ToInt32(indexList[i]);
                    dt.Rows.RemoveAt(index);
                }
                return dt;
            }
    
            /// <summary>   
            /// 判断数组中是否存在   
            /// </summary>   
            /// <param name="indexList">数组</param>   
            /// <param name="index">索引</param>   
            /// <returns></returns>   
            public static bool IsContain(ArrayList indexList, int index)
            {
                for (int i = 0; i < indexList.Count; i++)
                {
                    int tempIndex = Convert.ToInt32(indexList[i]);
                    if (tempIndex == index)
                    {
                        return true;
                    }
                }
                return false;
            }
            #endregion
    
    原文:https://blog.csdn.net/qq_23502409/article/details/75269221 
  • 相关阅读:
    python返回函数与匿名函数
    Session&Cookie
    write RE validation
    hello2 source anaylis
    Filter
    Development descriptor
    web.xml配置详解
    Annotation
    injector
    container
  • 原文地址:https://www.cnblogs.com/zhaoyl9/p/11236603.html
Copyright © 2020-2023  润新知