Domronic
Domronic

Reputation: 149

Checking if a range object is in a List

I have created a list of Range objects in C#

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

If am currently adding a reange to the list using the following:

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

This ends up with a List that has duplicate values. How can I use the Contains method on a List of complex types?

Upvotes: 0

Views: 519

Answers (1)

GJBisschop
GJBisschop

Reputation: 345

Instead of using the Contains function, you could use the All function and check the relevant properties to decide if it's an existing item.

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

Another way to solve this, is to implement the Equals function. See here for some more explanation.

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

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

Upvotes: 1

Related Questions