簡體   English   中英

如何在List(Of Integer())上做一個截然不同的?

[英]how to do a distinct on List(Of Integer())?

從此

(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提供自定義Equality比較器 - 否則您要比較引用,這是初始嘗試:

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> (除此之外,它們可以嵌套在嵌套列表上使用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM