2

我需要你的帮助。我正在尝试从对象列表中获取不同的值。我的课看起来像这样:

class Chromosome
{
    public bool[][] body { get; set; }
    public double fitness { get; set; }
}

现在我有List<Chromosome> population. 现在我需要的是一种方法,如何获得新列表:List<Chromosome> newGeneration. 这个新列表将仅包含来自原始列表的唯一染色体 - 种群。

染色体是独一无二的,当他的整个身体(在这种情况下是 2D 布尔数组)与其他染色体相比是独一无二的。 我知道,有类似 MoreLINQ 的东西,但我不确定我是否应该使用 3rd 方代码,我知道我应该覆盖一些方法,但我有点迷茫。所以我真的很感激一些很好的逐步描述,即使是白痴也可以完成:) THX

4

2 回答 2

5

首先,实现相等运算符(这进入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();
于 2013-06-09T15:55:47.420 回答
0
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();
于 2013-06-09T16:35:13.877 回答