算法部分:
两个字段作 Key,记录ID作Value,重复的记录会维护一个ID列表(List);
遍历完之后,List数据项大于 1 的便是有重复的记录组;
static string reRows() { //初始化datatable DataTable tblDatas = new DataTable("Datas"); tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); tblDatas.Columns[0].AutoIncrement = true; tblDatas.Columns[0].AutoIncrementSeed = 1; tblDatas.Columns[0].AutoIncrementStep = 1; tblDatas.Columns.Add("Product", Type.GetType("System.String")); tblDatas.Columns.Add("Version", Type.GetType("System.String")); tblDatas.Columns.Add("Description", Type.GetType("System.String")); tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "d" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "e" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "c" }); tblDatas.Rows.Add(new object[] { null, "a", "b", "e" }); //五条记录 ,(Version,Description)作主键,1,4重复;3,5重复。 //算法 Dictionary<string[], List<int>> dic = new Dictionary<string[], List<int>>(new EqualityComparer()); foreach (DataRow item in tblDatas.Rows) { string[] cur = new string[] { item["Version"].ToString(), item["Description"].ToString() }; if (dic.ContainsKey(cur)){ dic[cur].Add((int)item["ID"]); } else { List<int> ls = new List<int>(); ls.Add((int)item["ID"]); dic.Add(cur,ls); } } string result = ""; foreach (var item in dic.Values) { if (item.Count > 1) { foreach (var d in item) { result += d+" "; } result += ";"; } } return result; } public class EqualityComparer : IEqualityComparer<string[]> { public bool Equals(string[] x, string[] y) { return x[0] == y[0] && x[1] == y[1]; } public int GetHashCode(string[] obj) { return 1; } }