思路:将DataTable转成IEnumerable,然后就能调用Distinct方法了

转载自:菩提树下的杨过 http://yjmyzz.cnblogs.com/
using System.Collections.Generic; 
using System.Linq; 
using System.Data; 
using System; 

namespace ConsoleApplication2 

    
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"武汉""湖北"); 
            tbl.Rows.Add(
2"应城""湖北"); 
            tbl.Rows.Add(
3"武汉""湖北"); 

            IEnumerable 
<DataRow> r = tbl.AsEnumerable().Distinct(new CityComparer()); 
          
          

            
//到这一步,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 int GetHashCode(DataRow obj) 
        { 
            
return obj.ToString().GetHashCode(); 
        } 


    } 

相关文章:

  • 2021-11-28
  • 2021-10-29
  • 2022-12-23
  • 2021-07-31
  • 2022-12-23
  • 2021-09-26
猜你喜欢
  • 2021-12-27
  • 2021-06-02
  • 2021-11-23
  • 2022-12-23
  • 2021-06-14
  • 2021-07-15
  • 2022-12-23
相关资源
相似解决方案