转载自:菩提树下的杨过 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();
}
}
}
本文介绍了一个使用 C# 对 DataTable 进行去重的示例,通过自定义 CityComparer 类实现了基于城市字段的数据去重。该示例展示了如何创建 DataTable,添加列与数据,以及使用 LINQ 和自定义比较器进行去重操作。
9713

被折叠的 条评论
为什么被折叠?



