LINQ选择在不工作的DataTable不同 [英] LINQ Select distinct on DataTable not working

查看:201
本文介绍了LINQ选择在不工作的DataTable不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的数据表 - 比方说,名为 MyTable的

I have the following datatable - Let's say called MyTable:

Col1:    Col2:    Col3:    Col4:
1        abc      def      <null>
2        abc      def      ghi
1        abc      def      <null>
3        abc      def      <null>
1        abc      def      <null>

和我试图让不同的行:

Col1:    Col2:    Col3:    Col4:
1        abc      def      <null>
2        abc      def      ghi
3        abc      def      <null>



我尝试以下LINQ语句:

I tried the following LINQ statement:

MyTable = (From dr As DataRow In MyTable Select dr).Distinct.CopyToDataTable

但它的返回与重复行原来的数据表还给我。

But it's returning the original datatable with the repeated rows back to me.

我在做什么错的,如何才能让我的期望输出??

What am I doing wrong AND how can I get my desired output??

推荐答案

鲜明依赖对象的所有执行 IEquatable 和/或具有的GetHashCode 的明智实现和等于。在的DataRow 类...没有。它不检查每列的值是在等于方法相同,只是采用了默认的实现,这是说,它会检查引用相等,这是不是你想要的。

Distinct relies on the objects all implementing IEquatable and/or having sensible implementations of GetHashCode and Equals. The DataRow class...doesn't. It doesn't check that the value of each column is equal in the Equals method, it just uses the default implementation, which is to say that it checks that the references are equal, and that's not what you want.

您可以提供自己的的IEqualityComparer ,因为你不能改变在的DataRow 方法。

You can provide your own IEqualityComparer, since you can't change the methods in DataRow.

下面应该工作,如果你提供它的一个实例对鲜明

The following should work, if you provide an instance of it to to Distinct:

public class DataRowComparer : IEqualityComparer<DataRow>
{
    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;
        }
    }
}

这篇关于LINQ选择在不工作的DataTable不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆