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

问题描述 投票:0回答:1

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

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

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

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

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

c# excel-interop
1个回答
0
投票

代替使用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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.