LINQ在DataTable上选择distinct不起作用
我有以下数据 – 让我们说名为MyTable
:
Col1: Col2: Col3: Col4: 1 abc def 2 abc def ghi 1 abc def 3 abc def 1 abc def
而我正试图获得不同的行:
Col1: Col2: Col3: Col4: 1 abc def 2 abc def ghi 3 abc def
我尝试了以下LINQ语句:
MyTable = (From dr As DataRow In MyTable Select dr).Distinct.CopyToDataTable
但它正在将重复行返回原始数据表返回给我。
我做错了什么以及如何获得我想要的输出?
Distinct
依赖于所有实现IEquatable
和/或具有合理的GetHashCode
和Equals
实现的对象。 DataRow
类……没有。 它没有检查Equals
方法中每列的值是否相等,它只是使用默认实现,也就是说它检查引用是否相等,而这不是你想要的。
您可以提供自己的IEqualityComparer
,因为您无法更改DataRow
的方法。
如果您将其实例提供给Distinct
,则以下内容应该有效:
public class DataRowComparer : IEqualityComparer { public bool Equals(DataRow x, DataRow y) { for (int i = 0; i < x.Table.Columns.Count; i++) { if (!object.Equals(x[i], y[i])) return false; } return true; } public int GetHashCode(DataRow obj) { unchecked { int output = 23; for (int i = 0; i < obj.Table.Columns.Count; i++) { output += 19 * obj[i].GetHashCode(); } return output; } } }
试试这样;
var distinctRows = (from DataRow dRow in MyTable.Rows select new {col1=dRow["Col1"],col2=dRow["Col2"], col3=dRow["Col3"], col4=dRow["Col4"]}).Distinct(); foreach (var row in distinctRows) { // }
问题是DataTable
中的每个DataRow
都是一个不同的对象。 每个都是一个实例。
虽然@Servy的问题确实是这样做的正确方法 – 非常感谢Servy! 我还发现了另一种至少看起来更清洁的解决方案:
MyTable = MyTable.DefaultView.ToTable(True)
这允许您只询问不同的记录,但是通过LINQ的原始请求否定 – 想象一下,我将其添加到将来查看此问题的任何其他人。