質問

これはおそらく非常に簡単な質問です。私は単にコレクションから重複するバイト[] sを削除しようとしています。

デフォルトの動作は参照を比較することですので、IEQUALITYComparerの作成が機能しますが、そうではありません。

ハッシュセットと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
.

役に立ちましたか?

解決

GetHashCodeDistinctによって使用され、「そのまま」動作しません。

のようなものを試してみてください
int result = 13 * obj.Length;
for(int i = 0 ; i < obj.Length ; i++) {
    result = (17 * result) + obj[i];
}
return result;
.

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

PESFORY 、私はパフォーマンスの等価性テストも登録します:

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;
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top