public class ChromosomeBodyComparer : IEqualityComparer<Chromosome>
{
private bool EqualValues(bool[][] left, bool[][] right)
{
if (left.Length != right.Length)
{
return false;
}
return left.Zip(right, (x, y) => x.SequenceEquals(y)).All();
}
public bool Equals(Chromosome left, Chromosome right)
{
return EqualValues(left.body, right.body)
}
//implementing GetHashCode is hard.
// here is a rubbish implementation.
public int GetHashCode(Chromosome c)
{
int numberOfBools = c.body.SelectMany(x => x).Count();
int numberOfTrues = c.body.SelectMany(x => x).Where(b => b).Count();
return (17 * numberOfBools) + (23 * numberOfTrues);
}
}
调用者:
List<Chromosome> nextGeneration = population
.Distinct(new ChromosomeBodyComparer())
.ToList();