检查对象列表中是否存在对象

本文关键字:对象 存在 是否 列表 检查 | 更新日期: 2023-09-27 18:22:05

我需要的是用什么代码来替换这个:<-- code (exist) -->

我有一个在表中创建单元格的类。我将这些单元格存储在单元格列表中。

List<Cell> locations = new List<Cell>(); 

我正在查找该列表中是否存在单元格。我正在做以下事情:

cell_in_array(new Cell(x, y));
public bool cell_in_array(Cell cell)
{
    if(<-- code (exist) -->){
      return true;
    } else {
      return false
    }           
}

细胞类

public class Cell
{
    int x_pos; // column
    int y_pos;// row
    public Cell(int col, int row)
    {
        x_pos = col;
        y_pos = row;
    }
    public int getRow()
    {
        return y_pos;
    }
    public int getColumn()
    {
        return x_pos;
    }
    public int[] position()
    {
        int[] cell_loc = { x_pos, y_pos };
        return cell_loc;
    }
}

检查对象列表中是否存在对象

使用IEqualityComparer<Cell>的实现让您的生活变得轻松。我使用这个解决方案是因为也许你在某个地方需要seme逻辑。

public class CellComparer : IEqualityComparer<Cell>
{
    public bool Equals(Cell x, Cell y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        if (x.Column == y.Column && x.Row == y.Row) return true;
        return false;
    }
    public int GetHashCode(Cell cell)
    {
        int hCode = cell.Column ^ cell.Row;
        return hCode.GetHashCode();
    }
}

使用它很简单,如果你检查列表内容,你会发现它包含两个元素,因为第一个和最后一个添加的单元格是相同的。

var list = new HashSet<Cell>(new CellComparer());
list.Add(new Cell(0, 1));
list.Add(new Cell(1, 2));
list.Add(new Cell(0, 1));

感谢HashSet,他将使用您的CellComparer来避免Cell重复。

因此,使用auto属性而不是方法来返回字段的值。你的手机类必须是这样的:

public class Cell
{
    public Cell(int col, int row)
    {
        Column = col;
        Row = row;
    }
    public int Row { get; private set; }
    public int Column { get; private set; }
    public int[] Position
    {
        get { return new[] { Column, Row }; }
    }
}

您可以将IEquatable接口添加到Cell类:

public class Cell : IEquatable<Cell>

这需要类中的CCD_ 7方法CCD_

public bool Equals(Cell otherCell)

this Cell等于otherCell(例如this.getRow() == otherCell.getRow()等)时,您提供一个代码来告知

如果CellIEquatable,则可以在Cells列表中使用Contains方法。因此,在主代码中,可以使用locations.Contains(cell)而不是<-- code (exist) -->

您应该考虑使用Properties重写Cell类。

您可以使用linq来完成

public bool cell_in_array(Cell cell)
{
    return locations.Any(c => c.getColumn() == cell.getColumn() && 
                              c.getRow() == cell.getRow())         
} 

CCD_ 18将确定是否有任何元素匹配该条件。

您可以使用Any来确定序列中的任何元素是否满足条件:

locations.Any(c => c.getColumn() == cell.getColumn() && c.getRow() == cell.getRow())