0

I have the List inputColl of type MyValue with many duplicate keys:

myValue1.Id=100;
myValue2.Id=100;
...etc

And I have custom comparer to compare two MyValue elements by Id:

inputColl.Sort(myValueComparer);

What am I doing wrong?

Comparer:

public class MyValueComparerById : IComparer<MyValue>
{
    public int Compare(MyValue x, MyValue y)
    {
        if (x.Id == y.Id)
            return 0;
        else if (x.Id > y.Id)
            return -1;
        else if (x.Id < y.Id)
            return 1;

        return 0;
    }
}
Admiral Land
  • 2,304
  • 7
  • 43
  • 81

2 Answers2

4

Unless your equality comparer is not implemented badly, your solution should work.

But I suggest an easier approach, using linq:

inputCol = inputCol.OrderBy(o => o.Id).ToList();
Mihai Caracostea
  • 8,336
  • 4
  • 27
  • 46
4

You already have an int comparer so is better to use it instead of rewriting same logic:

public class MyValueComparerById : IComparer<MyValue>
{
    public int Compare(MyValue x, MyValue y)
    {
         return x.Id.CompareTo(y.Id);        
    }
}

** Update edit **

For further improvements maybe you might want to consider additional comparison in case of Id equality:

public class MyValueComparerById : IComparer<MyValue>
{
    public int Compare(MyValue x, MyValue y)
    {
        var firstResult = x.Id.CompareTo(y.Id);        
        if (firstResult == 0)
        {
            // I'm assuming that MyValue has an additional string property named 'SomeName'
            return x.SomeName.CompareTo(y.SomeName);
        }
        return firstResult;
    }
}
tomab
  • 2,061
  • 5
  • 27
  • 38