0

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?

Christopher Schneider
  • 3,745
  • 2
  • 24
  • 38
Domronic
  • 149
  • 1
  • 1
  • 11
  • **Hi, you cant try with this post:** https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property – gonzalo centurion Jan 15 '20 at 15:41
  • 1
    What are you trying to do? The root problem is that `Range` does not have equality defined, but it's unclear what the purpose of having a list of ranges is to know what the right approach is? Should you keep a list of strings that _represent_ the ranges instad? Or a `Dictionary`)? – D Stanley Jan 15 '20 at 15:45
  • What I am trying to do is get a list of unique ranges that I could then loop through and perform further actions on. I previously has a Dictionary as you propose but I was hoping using a List would make everything more concise. – Domronic Jan 15 '20 at 15:49
  • 1
    @Domronic The problem is that two ranges created from the same reference are different objects, so `Contains` will not detect duplicates. If you can use the reference (e.g. `"A1:B2"`) as a string key then a `Dictionary` will probably be better for performance as well. – D Stanley Jan 15 '20 at 17:06

1 Answers1

1

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;
    }
}
GJBisschop
  • 315
  • 1
  • 3
  • 12
  • I would caution that this method has a lot of COM property calls and may have terrible performance if called a lot. – D Stanley Jan 15 '20 at 17:05