Search code examples
c#linqicomparableicomparer

Custom Icomparer with argument


How would an IComparer that needs an argument be implemented (might not be relevant but I'm using it on Linq query)?

I suppose it should be called like this:

ListOfObjectsToSort.orderBy(x => x, myCustomComparer(argument));

And this is what i found on how to implement the IComparer but i can't figure out how to change it to pass the argument here:

public class MyComparer : IComparer<object>
{
    public int Compare(object x, object y)
    {
       // code will then return 1,-1 or 0

Solution

  • You can't add an argument to the Compare method or you violate the interface contract. Add a property to the class that can be used in the method:

    public class MyComparer : IComparer<object>
    {
        public int MyArgument {get; set;}
        public int Compare(object x, object y)
        {
           // code will then return 1,-1 or 0
           // use MyArgument within the method       
        }
    

    You can set it in the constructor:

    public MyComparer(int argument)
    {
        MyArgument = argument;
    }
    

    Then your syntax would be:

    var myCustomComparer = new MyComparer(argument);
    ListOfObjectsToSort.orderBy(x => x, myCustomComparer);
    

    or just

    ListOfObjectsToSort.orderBy(x => x, new MyComparer(argument));