Sry for bad english ...
DataTable示例
| ID_UEH | ID_F |
|......1......|...10...|
|......1......|...11...|
|......2......|...10...|
|......2......|...12...|
|......3......|...10...|
|......3......|...13...|
我想创建一个函数来检查是否有符合规范的行:
- “ID_UEH”列中的值不同,但“ID_F”列中的值相同,
我试过这个:
(from rowA in DataTableA.Select()
join rowB in DataTableA.Select()
on rowA["ID_F"] equals rowB["ID_F"]
where rowA["ID_UEH"] != rowB["ID_UEH"]).Count()
并且代码返回0
然后我试试这个:
(from rowA in DataTableA.Select()
join rowB in DataTableA.Select()
on rowA["ID_F"] equals rowB["ID_F"]
where rowA["ID_UEH"] != rowB["ID_UEH"] &&
rowA["ID_F"] == rowB["ID_F"]).Count()
并且代码返回6(DataTableA.Rows.Count = 6)
然后他们让我快点,我这样做了:
int numRows = 0;
foreach (DataRow rowA in DataTableA.Select())
{
numRows = tabela.Select(
"ID_UEH <> "+Convert.ToInt32(rowA["ID_UEH"]) + " AND " +
"ID_F= " + Convert.ToInt32(rowA["ID_F"])
).Length;
if (numRows > 1)
break;
}
并且代码返回我想要的内容。
我的问题是,我做错了什么?
答案 0 :(得分:1)
连接不起作用的原因是:您正在使用同一个表加入,因此您获得12行(6 + 6并且所有都具有相同ID_UEH
值的“对应”。所以3的正确结果也加倍了。
编辑:我认为这是您需要的,比我下面的第一种方法更具可读性:
var rows = dataTableA.AsEnumerable();
int count = rows.Count(r1 => rows
.Any(r2 => r1.Field<int>("ID_F") == r2.Field<int>("ID_F")
&& r1.Field<int>("ID_UEH") != r2.Field<int>("ID_UEH")));
这是LINQ,它可以为您提供正确的结果。但是,它的可读性不高:
int count = dataTableA.AsEnumerable()
.GroupBy(r => r.Field<int>("ID_F"))
.Sum(g =>
{
if (g.Count() == 1)
return 0;
var allIDUEH = g.Select(r => r.Field<int>("ID_UEH"));
return allIDUEH.Count(ueh1 => allIDUEH.Any(ueh2 => ueh1 != ueh2));
});
继续你的循环....如果它有效,因为它做的与你描述的不同。
答案 1 :(得分:0)
var c = DataTableA.AsEnumerable()
.GroupBy(r=>r.Field<int>("ID_F"))
.Where(g=>g.Count()>1 &&
g.GroupBy(r=>r.Field<int>("ID_UEH"))
.Where(a=>a.Count()>1).Count() > 1)
.Count();
答案 2 :(得分:0)
尝试以下方法:
var q = (from r in DataTableA.AsEnumerable()
group r by r.Field<int>("ID_F") into gr
let count = gr.Select(g => g.Field<int>("ID_UEH")).Distinct().Count()
select count > 1 ? count : 0).Sum();