使用 LINQ 查找多个属性中的重复项
给定一个具有以下定义的类:
public class MyTestClass
{
public int ValueA { get; set; }
public int ValueB { get; set; }
}
如何在 MyTestClass[] 数组中找到重复值?
例如,
MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };
包含重复项,因为有两个 MyTestClass 对象,其中 ValueA 和 ValueB 均 = 1
Given a class with the following definition:
public class MyTestClass
{
public int ValueA { get; set; }
public int ValueB { get; set; }
}
How can duplicate values be found in a MyTestClass[] array?
For example,
MyTestClass[] items = new MyTestClass[3];
items[0] = new MyTestClass { ValueA = 1, ValueB = 1 };
items[1] = new MyTestClass { ValueA = 0, ValueB = 1 };
items[2] = new MyTestClass { ValueA = 1, ValueB = 1 };
Contains a duplicate as there are two MyTestClass objects where ValueA and ValueB both = 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过按 ValueA 和 ValueB 对元素进行分组来查找重复项。
之后对它们进行计数,您会发现哪些是重复的。
这是隔离受骗者的方法:
You can find your duplicates by grouping your elements by ValueA and ValueB.
Do a count on them afterwards and you will find which ones are duplicates.
This is how you would isolate the dupes :
您可以同时使用 Jon Skeet 的
DistinctBy
和Except
来查找重复项。请参阅此回复了解他对DistinctBy< 的解释/代码>。
但它只会返回一项,而不返回两项重复项。
You could just use Jon Skeet's
DistinctBy
andExcept
together to find duplicates. See this Response for his explanation ofDistinctBy
.It will only return one item and not both duplicates however.
MyTestClass 应该实现 Equals 方法。
这里有一个 关于它的好文章。
之后,您可以使用“Distinct”方法获得 MyTestClass 的“干净”列表。
MyTestClass should implement the Equals method.
Here you have a good article about it.
After that you can get a "clean" list of MyTestClass with "Distinct" method.