【问题标题】:Duplicate rows in dataset数据集中的重复行
【发布时间】:2014-04-07 09:33:27
【问题描述】:

我有一个问题,我不知道该怎么做我有一个数据集,如果它有重复的行,那么我想打印一条消息。任何人都可以建议我如何做到这一点。下面是代码

bool ErrorOcc = false;
StringBuilder script = new StringBuilder();
string Filter = "";
string XmlCheck = "";
string[] IfExists = null;
for (int i = 0; i < ColumnsToks[0].Length; i++)
{
    if (ColumnsToks[0][i] != "")
    {
        xml += @"<" + objModule.TableName + ">";
        for (int j = 0; j < objModule.Cols.Count; j++)
        {
            MCol col = objModule.Cols[j];
            DataTable dt = EBusiness.GetModuleColsValidation(this.Data.MID, col.ID);
            if (dt.Select("ValidationOnClient = 'False' and ValidationType = 'Unique'").Length == 0)
            {

            }
            for (int m = 0; m < dt.Rows.Count; m++)
            {
                 if (!Convert.ToBoolean(dt.Rows[m]["ValidationOnClient"]) && dt.Rows[m]["ValidationType"].ToString() == "Unique")
                 {
                     //  Filter += col.ColName + "='" + ColumnsToks[j][i] + "' And ";
                     XmlCheck += col.ColName + "='" + ColumnsToks[j][i] + "',";
                  }
             }
             IfExists = XmlCheck.Split(",".ToCharArray());
             xml += "<" + col.ColName + ">" + ColumnsToks[j][i].Replace("<", "&lt;").Replace(">", "&gt;").Replace("&nbsp;", "") + "</" + col.ColName + ">";
         }
         bool IfDuplicate = false;
         foreach (string count in IfExists)
         {
             if (count != "")
             {
                 Filter += count + " and ";
             }
         }
         objData.Query = "select COUNT(*) from " + objModule.TableName + " where " + Filter + " 1=1 ";
         IfDuplicate = Convert.ToBoolean(objData.GetSingleValue());
         if (IfDuplicate)
         {
             script.Append("alert('Error - There are some Duplicate entries.'); ");
             ErrorOcc = true;
         }
         if (ErrorOcc)
         {
             this.ScriptOutput = script + " ValidateBeforeSaving = false;";
             this.StayContent = "yes";
             return;
         }
         if (DataSetupColumnName != "")
         {
             foreach (MModule module in dataSetupModules.Modules)
             {
                 xml += "<" + module.TableName + ">" + Request["d" + module.TableName] + "</" + module.TableName + ">";
             }
          }
          foreach (DataRow dr in dtChildModule.Rows)
          {
              if (Request["t" + dr["ParentModuleID"]] == "")
              {
                  this.Message = "Please select Parent Module ID.";
                  return;
              }
              xml += "<t" + dr["ParentModuleID"] + ">" + Convert.ToInt32("0" + Request["t" + dr["ParentModuleID"]]) + "</t" + dr["ParentModuleID"] + ">";
          }
          xml += "<Status>1</Status><CreatedBy>0</CreatedBy><UpdatedBy>0</UpdatedBy>";
          if (dtRestrictions.Rows.Count > 0)
          {
               xml += "<Level>" + GetLevel(EBusiness.GetCompanySetupModules(this.Data.WFID)) + "</Level>";
               xml += "<LevelDataID>" + Request["t" + Request["ParentModuleID"]] + "</LevelDataID>";
          }
          xml += "</" + objModule.TableName + ">";
      }
  }
  xml += "</Table>";
  DataSet dsXml = new DataSet();
  dsXml.ReadXml(new XmlTextReader(new StringReader(xml)));

【问题讨论】:

    标签: c# dataset


    【解决方案1】:

    有几种方法可以让它工作,我想到的前两种是使用 HashTables 或 LinQ 表达式。

    看看这个: Best way to remove duplicate entries from a data table 但不是删除重复项(查看第二个 foreach),而是打印消息。

    public void CheckDuplicateRows(DataTable dTable, string colName)
    {
       Hashtable hTable = new Hashtable();
       ArrayList duplicateList = new ArrayList();
    
       //Add list of all the unique item value to hashtable, which stores combination of     key, value pair.
       //And add duplicate item value in arraylist.
       foreach (DataRow drow in dTable.Rows)
       {
          if (hTable.Contains(drow[colName]))
             duplicateList.Add(drow);
          else
             hTable.Add(drow[colName], string.Empty); 
       }
    
      //Checks the list dimension to verify if there is any duplicate
      if(duplicateList.Count() > 0)
      {
      //you can print your message here or eventually get info about the duplicate row
      }   
    }
    

    【讨论】:

    • Thanx @Saverio 但我不想删除它我只需要打印一条消息
    • 我将编辑我的答案,向您展示一种可行的方法。
    【解决方案2】:

    这是我上述问题的答案

    您可以像这样检查 DataSet 中的重复行,它工作正常,试试吧:

    DataSet dsXml = new DataSet();
    dsXml.ReadXml(new XmlTextReader(new StringReader(xml)));
    
    List<string> duplicateList = new List<string>();
    foreach (DataRow drow in dsXml.Tables[0].Rows)
    {
        string strr = "";
    
        for (int j = 0; j < dsXml.Tables[0].Columns.Count; j++ )
        {
            strr += drow[j];
        }
    
        if (!duplicateList.Contains(strr))
        {
            duplicateList.Add(strr);
        }
        else
        {
            script.Append("alert('Error - There are some Duplicate entries.'); ");
            ErrorOcc = true;
            if (ErrorOcc)
            {
                this.ScriptOutput = script + " ValidateBeforeSaving = false;";
                this.StayContent = "yes";
                return;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      相关资源
      最近更新 更多