今天一位朋友问如何去掉DataTable里重复的记录(DataTable是别人返回过来的,不能再重新查询数据库,所以无法用sql中的select distinct xxx处理,只能在DataTable上动脑筋)
思路:将DataTable转成IEnumerable,然后就能调用Distinct方法了
by 菩提树下的杨过 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();
}
}
}
上面的代码,将DataTable中"城市名"重复的记录去掉了,以上代码同样适用于List<T>(只要改下"比较器"即可)