Sorting an object in Inventory by their name c#

Hi guys, I want to implement the Sorting System like found in the many games on their Inventory or that requires a Sorting System. So, I have found a way to implement the Sorting System in my game and I compare it with the Item Name that stored in the Item Manager class. However I got these following errors, both in the Unity itself and from the code.

Inside Unity:

Assets/Scripts/SortingList.cs(6,19):
error CS0539:
`System.Collections.IComparer.Compare’
in explicit interface declaration is
not a member of interface

Code:

I have these items in the Inventory:

32167-capture.png

and I want those items will be sorted automatically by their given name.

Here is the code that I am using:

Sorting List Class:

using UnityEngine;
using System.Collections;

public class SortingList : IComparer
{
    int IComparer.Compare(ItemManager x, ItemManager y)
    {
        return ((new CaseInsensitiveComparer()).Compare(((ItemManager)x).itemName, ((ItemManager)y).itemName));
    }
}

Inventory Class:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Inventory: MonoBehaviour
{
SortingList comparerMethod;

List<ItemManager> slots; // Hold all of the items in the inventory

void Start()
    {
        comparerMethod = new SortingList();
    }

void Update()
    {
        slots.Sort(comparerMethod); // This is where the error in the code shows.
    }
}

Item Manager Class:

using UnityEngine;
using System.Collections;

[System.Serializable]

public class ItemManager
{
    public string itemName;
}

Any help would be appreciated

Thanks

You need to use the generic version of the interface to work with the generic list.

You can use a Comparison method or the IComparer interface.

Currently you’re implementing the non-generic IComparer version, which takes the type object as parameter to the compare function. But you’re defining the comparison method as:

int IComparer.Compare(ItemManager x, ItemManager y)

If you change the code to:

using UnityEngine;
using System.Collections.Generic;
 
public class SortingList : IComparer<ItemManager>
{
    public int Compare(ItemManager x, ItemManager y)
    {
        return new CaseInsensitiveComparer().Compare(x.itemName, y.itemName);
    }
}

It should work.