我需要的是我应该替换的代码:<-- 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/