gpt4 book ai didi

c# - 如何对 List(Of Integer()) 进行区分?

转载 作者:行者123 更新时间:2023-11-30 19:29:50 24 4
gpt4 key购买 nike

自此

(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();

关于c# - 如何对 List(Of Integer()) 进行区分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com