How to delete duplicate data from dataset in asp.net

Source: Internet
Author: User

The data in DataTable is as follows:

Id key value
1 a aa
1 a aa
2 B bb
2 B bb
3 c cc
3 c cc

Now you want to make the able look like this

Id key value
1 a aa
2 B bb
3 c cc


Code

Void DeleteSameRow (DataSet ds)
  {
ArrayList indexList = new ArrayList ();
// Locate the row index to be deleted
For (int I = 0; I <ds. Tables [0]. Rows. Count-1; I ++)
  {
If (! IsContain (indexList, I ))
  {
For (int j = I + 1; j <ds. Tables [0]. Rows. Count; j ++)
  {
If (ds. tables [0]. rows [I] [AccountInfo. columns. AUName]. toString () = ds. tables [0]. rows [j] [AccountInfo. columns. AUName]. toString ())
  {
IndexList. Add (j );
  }
  }
  }
  }
// Delete a row based on the index list to be deleted
For (int I = indexList. Count-1; I> = 0; I --)
  {
Int index = Convert. ToInt32 (indexList [I]);
Ds. Tables [0]. Rows. RemoveAt (index );
  }
  }
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;
  }

Let's look at another instance.

/// <Summary>
/// Obtain a new able that does not repeat a fixed column
/// </Summary>
/// <Param name = "dt"> DataTable with duplicate data </param>
/// <Param name = "colName"> duplicate column names need to be verified </param>
/// <Returns> The New able and colName columns are not repeated, and the table format remains unchanged </returns>
Private DataTable GetDistinctTable (DataTable dt, string colName)
        { 
DataView dv = dt. DefaultView;
DataTable dtCardNo = dv. ToTable (true, colName );
DataTable Pointdt = new DataTable ();
Pointdt = dv. ToTable ();
Pointdt. Clear ();
For (int I = 0; I <dtCardNo. Rows. Count; I)
            { 
DataRow dr = dt. Select (colName "= '" dtCardNo. Rows [I] [0]. ToString () "'") [0];
Pointdt. Rows. Add (dr. ItemArray );
            } 
Return Pointdt;
        }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.