Skip to main content
 首页 » 编程设计

c#之在 DataRow 集合上调用 Distinct()

2024年01月29日27qlqwjy

尝试使用 Distinct() 扩展方法在数据表中查找唯一行。有些行包含完全相同的数据,但由于某种原因,这些行的哈希码彼此不同。

我写了一个实现 IEqualityComparer<DataRow> 的比较器类, 然而,我想我在做什么 GetHashCode()俗气又讨厌。

我这样做的原因是因为 Equals()除非哈希码相同(预期行为),否则永远不会被调用

class RowValidationComparer : IEqualityComparer<DataRow> 
        { 
            public bool Equals(DataRow x, DataRow y) 
            { 
                return x.Field<string>("MyField").Equals(y.Field<string>("MyField")); 
            } 
 
            public int GetHashCode(DataRow obj) 
            { 
                typeof(DataRow).GetHashCode(); 
            } 
        } 

请您参考如下方法:

Trying to find unique rows in a data table using Distinct() extension method.

为此,您可以使用 DataRowComparer类:

var distinct = dataTable.AsEnumerable().Distinct(DataRowComparer.Default); 

来自 MSDN 的一般解释, 讨论集合运算符的使用,例如 DataRows 上的 Distinct:

These operators compare source elements by calling the GetHashCode and Equals methods on each collection of elements. In the case of a DataRow, these operators perform a reference comparison, which is generally not the ideal behavior for set operations over tabular data. For set operations, you usually want to determine whether the element values are equal and not the element references. Therefore, the DataRowComparer class has been added to LINQ to DataSet. This class can be used to compare row values.

The DataRowComparer class contains a value comparison implementation for DataRow, so this class can be used for set operations such as Distinct.