检查范围对象是否在列表中

Checking if a range object is in a List

我已经在 C# 中创建了一个 Range 对象列表

private List<Excel.Range> _dataCells = new List<Excel.Range>();

如果当前正在使用以下方法向列表中添加范围:

if (_dataCells.Contains(_excel.Selection) == false)
{
    _dataCells.Add(_excel.Selection);
}

最后得到一个具有重复值的列表。如何在复杂类型列表上使用 Contains 方法?

除了使用 Contains 函数,您还可以使用 All 函数并检查相关属性以确定它是否为现有项目。

if (_dataCells.All(x => x.Selection.Property != _excel.Selection.Property))
{
    _dataCells.Add(_excel.Selection);
}

解决这个问题的另一种方法是实现 Equals 函数。有关更多说明,请参阅 here

public class Selection : IEquatable<Selection>
{
    ...

    public override bool Equals(Selection selection)
    {
        return selection != null && this.Property == selection.Property;
    }
}