当前位置:  开发笔记 > 编程语言 > 正文

使用GroupBy消除List <T>中的重复对象

如何解决《使用GroupBy消除List<T>中的重复对象》经验,为你挑选了1个好方法。



1> Yuval Itzcha..:

而不是GroupBy考虑实施IEquatable和使用Enumerable.Distinct.

public class ThreeDPoint : IEquatable
{
    public bool Equals(ThreeDPoint other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((ThreeDPoint) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            var hashCode = X.GetHashCode();
            hashCode = (hashCode*397) ^ Y.GetHashCode();
            hashCode = (hashCode*397) ^ Z.GetHashCode();
            return hashCode;
        }
    }

    public static bool operator ==(ThreeDPoint left, ThreeDPoint right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ThreeDPoint left, ThreeDPoint right)
    {
        return !Equals(left, right);
    }

    public ThreeDPoint(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public double X { get; private set; }
    public double Y { get; private set; }
    public double Z { get; private set; }
}

现在做:

var points = new List { // Add elements };
points.Distinct();

编辑:

如果你仍然相信你想要GroupBy(我肯定会推荐使用这种IEquatable方法),你可以这样做:

var list = new List 
{ 
    new ThreeDPoint(1.0, 2.0, 3.0), 
    new ThreeDPoint(1.0, 2.0, 3.0), 
    new ThreeDPoint(2.0, 2.0, 2.0), 
    new ThreeDPoint(2.0, 2.0, 2.0) 
};

var distinctResult = list.GroupBy(x => new { x.X, x.Y, x.Z })
                         .Select(x => x.First());

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有