可以自定义类 ,也可以从参考官网文档:Enumerable.Except 方法 (System.Linq) | Microsoft Learn
List<DataRow> list1 = new List<DataRow>(); List<DataRow> list2 = new List<DataRow>(); DataTable dataTable = new DataTable(); dataTable.Columns.Add("ID", typeof(int)); dataTable.Columns.Add("Name", typeof(string)); DataRow row1 = dataTable.NewRow(); row1["ID"] = 1; row1["Name"] = "Alice"; list1.Add(row1); DataRow row2 = dataTable.NewRow(); row2["ID"] = 2; row2["Name"] = "Bob"; list1.Add(row2); DataRow row3 = dataTable.NewRow(); row3["ID"] = 1; row3["Name"] = "Alice"; list2.Add(row3); DataRow row4 = dataTable.NewRow(); row4["ID"] = 3; row4["Name"] = "Dave"; list2.Add(row4); List<DataRow> result = list1.Except(list2, new DataRowComparer("ID")).ToList(); list1 = list1.Where(row => !list2.Contains(row, new DataRowComparer("ID"))).ToList(); list1.RemoveAll(row => list2.Contains(row)); foreach (DataRow row in list1) { Console.WriteLine(row["Name"]); } class DataRowComparer : IEqualityComparer<DataRow> { private readonly string _columnName; public DataRowComparer(string columnName) { _columnName = columnName; } bool IEqualityComparer<DataRow>.Equals(DataRow?x, DataRow?y) { if (x == null || y == null) { return false; } return x[_columnName].Equals(y[_columnName]); } int IEqualityComparer<DataRow>.GetHashCode(DataRow obj) { return obj[_columnName].GetHashCode(); } }
标签:取差集,自定义,C#,list1,ID,columnName,DataRow,list2,dataTable From: https://www.cnblogs.com/jiaozai891/p/17300864.html