c# - 检查对象列表中是否存在对象

标签 c# .net list equality

我需要的是我应该替换的代码:<-- 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> 的实现让您的生活更轻松. 我使用此解决方案是因为您可能在某处需要该语义逻辑。

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重复。

因此使用自动属性而不是方法来返回字段的值。您的单元格类必须如下所示:

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 }; }
    }
}

关于c# - 检查对象列表中是否存在对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712900/

相关文章:

c# - 为什么现在类倾向于定义为接口(interface)?

c# - 使用 SMO 更改 SQL Server 数据库默认位置

c# - PropertyChangedEventArgs 格式异常

asp.net - DropdownList 重置在更新面板的提交按钮上不起作用

c# - 以编程方式使用附加字段扩展 Lucene 文档

c# - REGEX C#(匹配开头和结尾单词)

python - 如何用 numpy 命令替换列表理解?

列出与文件关联的缓冲区?

python - 拆分列表中的整数(python)

c# - 如何在 C# 中使用变量调用对象的属性,例如客户.&fieldName