0

How can i convert this java style code into C# ? Here is what i have tried already :

I changed the method name from comparable(java) to icompare(c#).

Array.Sort(valobject,  new IComparer(){

            public int Compare(Object obj1, Object obj2) {
                String label1 = ((valobject) obj1).getLabel();
                String label2 = ((valobject) obj2).getLabel();

                if (label1 == null) {
                    if (label2 == null) {
                        return 0;
                    } else {
                        return -1;
                    }
                } else {
                    if (label2 == null) {
                        return 1;
                    } else {
                        return (new CaseInsensitiveComparer()).Compare(label1, label2 ) ;  
                    }
                }
            }

        });
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Undisputed007
  • 639
  • 1
  • 10
  • 31

1 Answers1

2

Just define an implementation of IComparer and pass its instance to Sort method. There are no anonymous classes in C#.

EDIT:

There is in fact an overload of Array.Sort that takes Comparison delegate so that it is possible to use lambda function directly:

Array.Sort(valobject, (obj1, obj2) => 
{
    String label1 = ((valobject) obj1).getLabel();
    String label2 = ((valobject) obj2).getLabel();
    // ...
    // ...all the rest of the comparison logic
});
  • Thank you, i will try to do that, thought there was an easier way like in Java, – Undisputed007 Nov 13 '15 at 13:20
  • 1
    You can create a universal `IComparer` implementation that takes a lambda function in its constructor and then performs comparison with the help of that function. This way you can imitate Java’s anonymous classes behaviour for `IComparer` interface. – Dzmitry Sauchanka Nov 13 '15 at 13:22
  • Your answer worth upvote if you put this comment in answer and also with an example ;) – M.kazem Akhgary Nov 13 '15 at 13:26
  • Oh, there is even a `Sort` overload that takes `Comparison` delegate so no need for special `IComparer` implementation as I supposed in the previous comment. – Dzmitry Sauchanka Nov 13 '15 at 13:35
  • Thank you. and i hope this can help others in the future. Without the question getting closed for "some" reasons. – Undisputed007 Nov 13 '15 at 13:40