C#类实例比较,截然不同 [英] C# class instance comparison, distinct
问题描述
Hello Guys,
我想知道是否有人知道更好的方法来获得与List< some_class>的区别没有使用任何助手类。
目前我有这个(我简化了这个):
Hello Guys,
I was wondering if anyone knows a better way to get a distinct from List<some_class> not using any helper classes.
Currently I have this (I have simplified this):
class A
{
int X, Y;
public A(int xx, int yy)
{ X = xx; Y = yy;}
}
//this is a helper class I want to get rid of
class helper : IEqualityComparer<A>
{
public bool Equals(A x, A y)
{return x.X == y.X && x.Y == y.Y;}
public int GetHashCode(A obj)
{return 0;}
}
List<A> class_array = new List<A>
class_array.Add(new A(1, 1));
class_array.Add(new A(1, 1));
class_array.Add(new A(2, 2));
class_array.Add(new A(2, 2));
class_array = class_array.Distinct(new helper()).ToList()
任何人都知道更好的解决方案吗?我需要这个的原因是我有多个类数组要比较,我真的不希望每个都有帮助比较类...这听起来不对...
提前谢谢!
Anyone know a better solution for the situation? The reason I need this is that I have multiple class arrays to compare and I dont really want to have helper comparison classes for each... This just does not sound right...
Thank you in advance!
推荐答案
来自文档 [ ^ ]:
默认的相等比较器Default用于比较值实现 IEquatable< t> [ ^ ]通用界面。要比较自定义数据类型,您需要实现此接口并为该类型提供自己的GetHashCode和Equals方法。
所以类A
需要实现此界面。
-Edit-
这对我来说很好:
From the documentation[^]:
The default equality comparer, Default, is used to compare values of the types that implement the IEquatable<t>[^] generic interface. To compare a custom data type, you need to implement this interface and provide your own GetHashCode and Equals methods for the type.
So classA
would need to implement this interface.
-Edit-
This works fine for me:
class A : IEquatable<A>
{
int X, Y;
public A(int xx, int yy) { X = xx; Y = yy; }
public override bool Equals(object other) { return Equals((A)other); } // Note that this implementation doesn't follow proper standards. Always check for null values, or objects of a different type and handle them accordingly.
public bool Equals(A other) { return X == other.X && Y == other.Y; }
public override int GetHashCode() { return (X + Y).GetHashCode(); }
}
尝试如下。
注意: 我没有测试。请检查。
Try is as below.
Note:I didn't test.Please check that.
List<A> distinct =
class_array
.GroupBy(a => new {a.X,a.Y})
.Select(g => g.First())
.ToList();
仅用于变化:
List<A> ADeDupe = class_array
.Select(a => new {X = a.X, Y = a.Y})
.Distinct()
.ToList()
.Select(a => new A(a.X, a.Y))
.ToList();
imho,如果实现自定义Comparer,将来您的代码将更易于维护,并简单地使用'Distinct,而不是使用棘手的Linq。
imho, your code will be more maintainable in the future if you implement the custom Comparer, and simply use 'Distinct, rather than using "tricky" Linq.
这篇关于C#类实例比较,截然不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!