Help with comparers

Hi,

I’m wondering whats the correct and easiest way to pass a comparison function to a custom object to use for checking if two objects are the same.

To give more detail, i have a generic inventory class, and in it’s constructor I pass the comparer function that I wish to use later to determine if an two objects/items match.

Here’s my code,

public class CGInventory<T1>
{
    public class CGInventoryItem
    {
        public int amount;
        public T1 item;

        public CGInventoryItem(int amount, T1 item)
        {
            this.amount = amount;
            this.item = item;
        }
    }


    public List<CGInventoryItem> items = new List<CGInventoryItem>();
    private Comparison<T1> groupingComparer;


    public CGInventory(Comparison<T1> groupingComparer)
    {
        this.groupingComparer = groupingComparer;
    }


    private CGInventoryItem Get(T1 searchItem)
    {
        foreach (CGInventoryItem item in items)
        {
            if (groupingComparer.Compare(searchItem, item.item) == 0)
            {
                return item;
            }
        }
        return null;
    }

And this is how I would like to use it:

public class SurvivalInventory : CGInventory<SurvivalItem>
{
    public static int CompareItem(SurvivalItem x, SurvivalItem y)
    {
        return ((new CaseInsensitiveComparer()).Compare(y.itemName, x.itemName));
    }

    public SurvivalInventory(bool groupingEnabled, Comparer groupingComparer) : base(true, CompareItem)
    {
       
    }

}

It doesn’t know how to use
groupingComparer.Compare

everything else compiles

Thanks,
Primoz

Copy the actual error message. Especially when you don’t know what it means.

I suspect you are confusing Comparison and Comparer–the former is a delegate type, the latter is a class. You’ve defined your variable as the former but you’re trying to invoke it like the latter.

error CS1061: ‘Comparison’ does not contain a definition for ‘Compare’ and no accessible extension method ‘Compare’ accepting a first argument of type ‘Comparison’

I am certain i’m confusing comparison, comparer, icomparer and everything else in between. I tried all of them and none have really given me a good result. I can see that if I pass my function to a List.Sort it works fine, so i would like to do a similar thing.

How do i actually invoke the Comparison class correctly?

It’s not a class, it’s a delegate. Delegates are basically references to functions. Treat it like a function.

if (groupingComparer(searchItem, item.item) == 0)

Of course, you should probably change the name if you’re going to keep it as a Comparison rather than a Comparer.

Thank you so much that worked perfectly