转载自:菩提树下的杨过 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();
}
}
}
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();
}
}
}