Datatable and list methods for deduplication

Source: Internet
Author: User

Today, a friend asked me how to remove the repeated records in the datatable. (The datatable is returned by someone else and cannot query the database again. Therefore, the Select distinct XXX in SQL cannot be used for processing, you can only use your mind on datatable)

Idea: Convert datatable to ienumerable, and then you can call the distinct method.

By poplar http://yjmyzz.cnblogs.com under the bodhi tree/

Using System. Collections. Generic;
Using System. LINQ;
Using System. Data;
Using System;

Namespace Leleapplication2
{
Class Program
{
Static   Void Main ( String [] ARGs)
{
Datatable TBL =   New Datatable ();
TBL. Columns. Add ( " ID " , Typeof (System. int32 ));
TBL. Columns. Add ( " City " , Typeof (System. String ));
TBL. Columns. Add ( " Province " , Typeof (System. String ));

TBL. Rows. Add ( 1 , " Wuhan " , " Hubei Province " );
TBL. Rows. Add ( 2 , " Yingcheng " , " Hubei Province " );
TBL. Rows. Add ( 3 , " Wuhan " , " Hubei Province " );

Ienumerable<Datarow>R=TBL. asenumerable (). Distinct (NewCitycomparer ());

// In this step, the record is repeated in R.

Foreach (VAR item In R)
{
Console. writeline (item [ " ID " ] +   " , "   + Item [ " City " ] +   " , "   + Item [ " Province " ]);
}

Console. Readline ();
}


}

Class Citycomparer: iequalitycomparer < Datarow >  
{
Public   Bool Equals (datarow R1, datarow R2)
{
Return R1 [ " City " ] = R2 [ " City " ];
}

Public IntGethashcode (datarow OBJ)
{
ReturnOBJ. tostring (). gethashcode ();
}

}
}

 

The aboveCodeRemove the record with duplicate "city name" in datatable. The code above applies to list <t> (just change it to "comparator)

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.