C#:比较自定义类的两个 ArrayList 并找到重复项 [英] C#: Compare two ArrayList of custom class and find duplicates

查看:21
本文介绍了C#:比较自定义类的两个 ArrayList 并找到重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 ArrayList 数组.

I have two arrays of ArrayList.

public class ProductDetails
{
    public string id;
    public string description;
    public float rate;
}

ArrayList products1 = new ArrayList();
ArrayList products2 = new ArrayList();
ArrayList duplicateProducts = new ArrayList();

现在我想要的是让所有产品(包含 ProductDetails 类的所有字段)在 products1products2 中都有重复的描述.

Now what I want is to get all the products (with all the fields of ProductDetails class) having duplicate description in both products1 and products2.

我可以像传统方式一样运行两个 for/while 循环,但是如果两个数组中的元素都超过 10k,那将会非常慢.

I can run two for/while loops as traditional way, but that would be very slow specially if I will be having over 10k elements in both arrays.

所以也许可以用 LINQ 做一些事情.

So probably something can be done with LINQ.

推荐答案

如果您想使用 linQ,您需要编写自己的 EqualityComparer,您可以在其中覆盖 EqualsGetHashCode()

If you want to use linQ, you need write your own EqualityComparer where you override both methods Equals and GetHashCode()

 public class ProductDetails
    { 
        public string id {get; set;}
        public string description {get; set;}
        public float rate {get; set;}
    }

public class ProductComparer : IEqualityComparer<ProductDetails>
{

    public bool Equals(ProductDetails x, ProductDetails y)
    {
        //Check whether the objects are the same object. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether the products' properties are equal. 
        return x != null && y != null && x.id.Equals(y.id) && x.description.Equals(y.description);
    }

    public int GetHashCode(ProductDetails obj)
    {
        //Get hash code for the description field if it is not null. 
        int hashProductDesc = obj.description == null ? 0 : obj.description.GetHashCode();

        //Get hash code for the idfield. 
        int hashProductId = obj.id.GetHashCode();

        //Calculate the hash code for the product. 
        return hashProductDesc ^ hashProductId ;
    }
}

现在,假设你有这个对象:

Now, supposing you have this objects:

ProductDetails [] items1= { new ProductDetails { description= "aa", id= 9, rating=2.0f }, 
                       new ProductDetails { description= "b", id= 4, rating=2.0f} };

ProductDetails [] items= { new ProductDetails { description= "aa", id= 9, rating=1.0f }, 
                       new ProductDetails { description= "c", id= 12, rating=2.0f } };


IEnumerable<ProductDetails> duplicates =
    items1.Intersect(items2, new ProductComparer());

这篇关于C#:比较自定义类的两个 ArrayList 并找到重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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