如何在 List(Of Integer()) 上做一个不同的
本文关键字:一个 List Of Integer | 更新日期: 2023-09-27 18:36:23
因为
(vb.net)
Dim test As New List(Of Integer())
test.Add(New Integer() {1, 2, 3})
test.Add(New Integer() {1, 3, 3})
test.Add(New Integer() {3, 2, 3})
test.Add(New Integer() {1, 1, 3})
test.Add(New Integer() {1, 2, 3})
Dim a = test.Distinct
(C#)
List<int[]> test = new List<int[]>();
test.Add(new int[] { 1, 2, 3 });
test.Add(new int[] { 1, 3, 3 });
test.Add(new int[] { 3, 2, 3 });
test.Add(new int[] { 1, 1, 3 });
test.Add(new int[] { 1, 2, 3 });
var a = test.Distinct();
不行,你会怎么区分?
在这种情况下,
您必须提供一个自定义的相等比较器才能Distinct
工作 - 否则您正在比较引用,这是初步尝试:
class SequenceComparer<T,U> : IEqualityComparer<T> where T: IEnumerable<U>
{
public bool Equals(T x, T y)
{
return Enumerable.SequenceEqual(x, y);
}
public int GetHashCode(T obj)
{
int hash = 19;
foreach (var item in obj)
{
hash = hash * 31 + item.GetHashCode();
}
return hash;
}
}
现在您可以在调用Distinct()
时使用它:
var results = test.Distinct(new SequenceComparer<int[],int>())
.ToList();
使用Distinct
重载,您可以在其中提供IEqualityComparer
并实现它以比较两个列表。
最小实现:
class ListComparer<T> : IEqualityComparer<List<T>> {
public bool Equals(List<T> a, List<T> b) {
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
if (! a[i].Equals(b[i])
return false;
return true;
}
public int GetHashCode(List<T> a) {
int ret = 11;
unchecked {
foreach (var x in a)
ret = ret * 17 + x.GetHashCode();
}
return ret;
}
}
但是一个真正的实现应该有第二个构造函数接受IEqualityComparer<T>
(除其他外,以便它们可以嵌套在嵌套列表中)。