使用Linq 来解决Datatable 去除数据重复
在这也说明下,除此之外还可以通过 DataView 的方式来处理,当个人觉得这有点不好用。这里就不多作说明了
代码比较简单,直接看代码
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace DTS { class Program { static void Main(string[] args) { DataTable _dt = new DataTable(); _dt.Columns.Add("id", typeof(int)); _dt.Columns.Add("name", typeof(string)); _dt.Columns.Add("address", typeof(string)); DataRow _dr = _dt.NewRow(); _dr["id"] = 1; _dr["name"] = "xiaodong"; _dr["address"] = "beijing"; _dt.Rows.Add(_dr); _dt.Rows.Add(_dr.ItemArray); _dt.Rows.Add(_dr.ItemArray); _dr = _dt.NewRow(); _dr["id"] = 2; _dr["name"] = "xiaodong"; _dr["address"] = "shanghai"; _dt.Rows.Add(_dr); _dr = _dt.NewRow(); _dr["id"] = 3; _dr["name"] = "xiaoming"; _dr["address"] = "guangdong"; _dt.Rows.Add(_dr); _dr = _dt.NewRow(); _dr["id"] = 4; _dr["name"] = "xudaxia"; _dr["address"] = "fujian"; _dt.Rows.Add(_dr); _dt.Rows.Add(_dr.ItemArray); Console.WriteLine("--------------------原来有重复数据的Table----------------------"); _dt.AsEnumerable().ToList().ForEach( m=> { Console.WriteLine(m["id"].ToString() + " " + m["name"].ToString() + " " + m["address"].ToString()); }); Console.WriteLine("--------------------去除重复后的Table----------------------"); var _comPresult = _dt.AsEnumerable().Distinct(new DataTableRowCompare()); DataTable _resultDt = _comPresult.CopyToDataTable(); _resultDt.AsEnumerable().ToList().ForEach( x => { Console.WriteLine(x["id"].ToString() + " " + x["name"].ToString() + " " + x["address"].ToString()); }); Console.Read(); } public class DataTableRowCompare : IEqualityComparer<DataRow> { #region IEqualityComparer<DataRow> 成员 public bool Equals(DataRow x, DataRow y) { return ((x.Field<int>("id") == y.Field<int>("id") && x.Field<string>("name") == y.Field<string>("name") && x.Field<string>("address") == y.Field<string>("address"))); } public int GetHashCode(DataRow obj) { return obj.ToString().GetHashCode(); } #endregion } } }
昨晚(2015-10-11)想了个对以上代码优化的办法,事比较多早上补上:
public static DataTable DistinctSomeColumn(DataTable sourceTable, params string[] fieldName) { if (fieldName == null || fieldName.Length == 0) return sourceTable; return sourceTable.AsEnumerable().Distinct(new ColumnEquals(fieldName)).CopyToDataTable(); } public class ColumnEquals : IEqualityComparer<DataRow> { public ColumnEquals(string[] sArr) { _sArr = sArr; } private string[] _sArr; public bool Equals(DataRow x, DataRow y) { return !_sArr.Any(p => !x[p].Equals(y[p])); } public int GetHashCode(DataRow dr) { return dr.ToString().GetHashCode(); } }