2

これはおそらく非常に単純な質問になります。コレクションから重複するbyte[]を削除しようとしています。

デフォルトの動作は参照を比較することなので、IEqualityComparerの作成は機能すると思いましたが、機能しません。

HashSetとLINQのDistinct()を使用してみました。

サンプルコード:

using System;
using System.Collections.Generic;
using System.Linq;

namespace cstest
{
    class Program
    {
        static void Main(string[] args)
        {
            var l = new List<byte[]>();
            l.Add(new byte[] { 5, 6, 7 });
            l.Add(new byte[] { 5, 6, 7 });
            Console.WriteLine(l.Distinct(new ByteArrayEqualityComparer()).Count());
            Console.ReadKey();
        }
    }

    class ByteArrayEqualityComparer : IEqualityComparer<byte[]>
    {
        public bool Equals(byte[] x, byte[] y)
        {
            return x.SequenceEqual(y);
        }

        public int GetHashCode(byte[] obj)
        {
            return obj.GetHashCode();
        }
    }
}

出力:

2
4

1 に答える 1

5

GetHashCodeによって使用されDistinct、「そのまま」は機能しません。次のようなものを試してください:

int result = 13 * obj.Length;
for(int i = 0 ; i < obj.Length ; i++) {
    result = (17 * result) + obj[i];
}
return result;

これは、ハッシュコードに必要な等式条件を提供する必要があります。

個人的には、パフォーマンスの同等性テストも展開します。

if(ReferenceEquals(x,y)) return true;
if(x == null || y == null) return false;
if(x.Length != y.Length) return false;
for(int i = 0 ; i < x.Length; i++) {
    if(x[i] != y[i]) return false;
}
return true;
于 2010-07-25T14:39:39.030 に答える