【问题标题】:check duplicate rows on condition in datatable using linq使用 linq 检查数据表中条件的重复行
【发布时间】:2014-05-13 13:11:37
【问题描述】:

我有一个datatable。它有 5 列(类型、A1、A2、B1、B2) 如果类型是 A,我想确保没有 2 行在 A1 和 A2 列中具有相同的数据,并且 对于 B 类,没有 2 行在 B1 和 B2 列中具有相同的数据 例如

Type | A1 | A2 | B1 | B2 | -------------------------- 1 A | 123 | XY | | | 2 A | 123 | XY | | | 3 B | | | TT | LL | 4 A | 456 | YZ | | | 5 B | | | TT | LL | 6 A | 123 | YZ | | | 7 B | | | TT | LL | 8 A | 456 | YZ | | |

在这种情况下,我想在第 1、2、4、8 行标记错误 以及第 3、5、7 行的另一个错误。

第 6 行没问题。

首先我在 Key= Type as 上完成了 Group by:

var groups = dt.AsEnumerable().GroupBy(r => r["Type"]).ToList();

我不确定是否在每个组上进一步使用 for-each 或者在 linq 中是否有更好的方法。 请指导。 谢谢。

【问题讨论】:

  • “我想标记一个错误”你想删除重复项还是你想要什么?
  • 我想将RowError 设置为该行。

标签: c# linq foreach datatable


【解决方案1】:

您可以为GroupBy 使用匿名类型:

var dupGroups = table.AsEnumerable()
    .Select(r => new{ 
        Row = r,
        IsA = r.Field<string>("Type")=="A",
        IsB = r.Field<string>("Type")=="B",
        A1 = r.Field<string>("A1"),
        A2 = r.Field<string>("A2"),
        B1 = r.Field<string>("B1"),
        B2 = r.Field<string>("B2"),
    })
    .GroupBy(x => x.IsA ? new { Val1 = x.A1, Val2 = x.A2 } : new { Val1 = x.B1, Val2 = x.B2 })
    .Where(g => g.Count() > 1);

foreach (var dupGroup in dupGroups)
    foreach (DataRow row in dupGroup.Select(x => x.Row))
        row.RowError = "Duplicate detected";

结果:

DataTable errors = table.GetErrors().CopyToDataTable();

1   A   123     XY      
2   A   123     XY      
3   B               TT      LL
4   A   456     YZ      
5   B               TT      LL
7   B               TT      LL
8   A   456     YZ  

如您所见,第 6 行不是错误表的一部分,因为它不是重复的。

【讨论】:

  • 感谢您的努力,但它在第二个新关键字处给了我Type of conditional expression cannot be determined because there is no implicit conversion between 'AnonymousType#1' and 'AnonymousType#2' for conditional operator(?:) 的错误。
  • @parixit:我已经用您的样本数据对其进行了测试。它是相同的匿名类型,因为它们具有相同的属性Val1Val2。您是否也在使用 .NET 4 或更高版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多