Eliminar bytes[] duplicados de una colección
-
29-09-2020 - |
Pregunta
Probablemente esta será una pregunta extremadamente sencilla.Simplemente estoy intentando eliminar bytes duplicados de una colección.
Dado que el comportamiento predeterminado es comparar referencias, pensé que crear un IEqualityComparer funcionaría, pero no es así.
Intenté usar HashSet y Distinct() de LINQ.
Código de muestra:
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();
}
}
}
Producción:
2
Solución
El GetHashCode
será utilizado por Distinct
, y no funcionará "tal cual";prueba algo como:
int result = 13 * obj.Length;
for(int i = 0 ; i < obj.Length ; i++) {
result = (17 * result) + obj[i];
}
return result;
lo que debería proporcionar las condiciones de igualdad necesarias para los códigos hash.
Personalmente, también desenrollaría la prueba de igualdad de rendimiento:
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;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow