C# 操作datatable校验重复行,并显示行号

 

  • 大体思路,在上传后,在datable末尾动态添加一列row_id,然后需要给row_id赋值
       DataColumn idColumn = new DataColumn();
                idColumn.DataType = System.Type.GetType("System.Int32");//该列的数据类型 
                idColumn.ColumnName = "row_id ";
                tableRepeat.Columns.Add(idColumn);
                if (tableRepeat != null && tableRepeat.Rows.Count > 0)
                {
                    int line = 3;
                    foreach (DataRow dr in tableRepeat.Rows)
                    {
                        dr[columnCount] = line;
                        line = line + 1;
                    }
                }
  • 比如查询手机号重复行,根据手机号分组,找出重复>1的行,然后根据手机号查询出行号
       //校验手机号
            var query_mobile = from f in tableParam.AsEnumerable()
                               group f by f.Field<string>("手机号") into m
                               where m.Count() > 1
                               select m.Key;
            if (query_mobile.Any())
            {
                foreach (var item in query_mobile.ToList())
                {
                    List<int> query_row = tableParam.AsEnumerable().AsParallel().Where(m => m.Field<string>("手机号") == item.Trim()).Select<DataRow, int>(dr => int.Parse(dr[tableParam.Columns.Count - 1].ToString())).ToList();
                    if (query_row.Any())
                    {
                        var msg = $"第{string.Join("、", query_row.Take(5).OrderBy(m => m))}行{(query_row.Count >= 5 ? "等共" + query_row.Count + "行" : "")}{ErrorExpandEnum.手机号重复.ToString()},请检查";
                        return msg;
                    }
                }
            }

 

上一篇:c# DataTable获取某个列的集合


下一篇:C#通用分页