来自对象列表的不同值

时间:2013-06-09 15:50:18

标签: c# linq distinct-values

我需要你的帮助。我试图从对象列表中获取不同的值。 我的班级看起来像这样:

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

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

染色体是独特的,当他的整个身体(在这种情况下是2D bool阵列)是唯一的比较到其他染色体。 我知道,有一些像MoreLINQ,但我不确定,我是否应该使用第三方代码,我知道我应该覆盖一些方法,但我有点迷失。所以我真的很感激一些好的一步一步的描述,甚至白痴都可以完成:) THX

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();
相关问题