请查看以下内容:
DataTable newTable = new DataTable();
DataColumn colRMID = new DataColumn();
colRMID.DataType = typeof(System.Int32);
colRMID.ColumnName = "RMID";
DataColumn colCpty = new DataColumn();
colCpty.DataType = typeof(System.String);
colCpty.ColumnName = "Cpty";
newTable.Columns.Add(colRMID);
newTable.Columns.Add(colCpty);
DataRow r1 = newTable.NewRow();
r1["RMID"] = 1234;
r1["Cpty"] = "Internal";
newTable.Rows.Add(r1);
DataRow r2 = newTable.NewRow();
r2["RMID"] = 5678;
r2["Cpty"] = "Wales Fargo";
newTable.Rows.Add(r2);
DataRow r3 = newTable.NewRow();
r3["RMID"] = 1234;
r3["Cpty"] = "External";
newTable.Rows.Add(r3);
DataRow r4 = newTable.NewRow();
r4["RMID"] = 9876;
r4["Cpty"] = "Internal";
newTable.Rows.Add(r4);
我想删除所有重复的行(具有相同的“RMID”),其中“Cpty”=“Internal”。 这样我在数据表中的最终输出应该是:
RMID Cpty
5678 "Wales fargo"
1234 "External"
9876 "Internal"
我需要使用LINQ
谢谢, 阿比纳夫
答案 0 :(得分:2)
这不是完全有效,但它是冗长的并且证明了这个概念。它还会产生您想要的结果。我相信你可以清理它以更好地满足你的需求。
var excludes = newTable
.AsEnumerable()
.GroupBy(row => row.Field<int>("RMID"))
.Select(groupedRows => new { Rows = groupedRows, Count = groupedRows.Count() })
.Where(groupedRows => groupedRows.Count > 1)
.Select(groupedRows => groupedRows.Rows.Single(row => row.Field<string>("Cpty") == "Internal"))
.Select(row => new { Rmid = row.Field<int>("RMID"), Cpty = row.Field<string>("Cpty") });
var filteredSet = newTable
.AsEnumerable()
.Select(row => new { Rmid = row.Field<int>("RMID"), Cpty = row.Field<string>("Cpty") })
.Except(excludes);