与对象列表不同的值
本文关键字:对象 列表 | 更新日期: 2023-09-27 18:17:49
我需要你的帮助。我正在尝试从对象列表中获取不同的值。我的类看起来像这样:
class Chromosome
{
public bool[][] body { get; set; }
public double fitness { get; set; }
}
现在我有List<Chromosome> population
.现在我需要的是一种方法,如何获得新列表:List<Chromosome> newGeneration
。这个新列表将仅包含原始列表中的独特染色体 - 人口。
首先,实现相等运算符(这进入class Chromosome
(:
public class Chromosome : IEquatable<Chromosome>
{
public bool[][] body { get; set; }
public double fitness { get; set; }
bool IEquatable<Chromosome>.Equals(Chromosome other)
{
// Compare fitness
if(fitness != other.fitness) return false;
// Make sure we don't get IndexOutOfBounds on one of them
if(body.Length != other.body.Length) return false;
for(var x = 0; x < body.Length; x++)
{
// IndexOutOfBounds on inner arrays
if(body[x].Length != other.body[x].Length) return false;
for(var y = 0; y < body[x].Length; y++)
// Compare bodies
if(body[x][y] != other.body[x][y]) return false;
}
// No difference found
return true;
}
// ReSharper's suggestion for equality members
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((Chromosome)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((this.body != null ? this.body.GetHashCode() : 0) * 397) ^ this.fitness.GetHashCode();
}
}
}
然后,使用 Distinct
:
var newGeneration = population.Distinct().ToList();
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();