コレクションからの重複バイト[] sを削除します
-
29-09-2020 - |
質問
これはおそらく非常に簡単な質問です。私は単にコレクションから重複するバイト[] 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
. 解決
GetHashCode
はDistinct
によって使用され、「そのまま」動作しません。
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;
. 所属していません StackOverflow