Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a custom Comparer to sort an Array in a different lexical order?

So, I'm pretty new to C# and I'm trying to order an Array using a custom Comparer.

I created a class:

class MySorter : IComparer
{
    public int Compare(object x, object y)
    {
        var chars = "jngmclqskrzfvbwpxdht";
        if (chars.IndexOf((char)x) < chars.IndexOf((char)y))
            return -1;
        return chars.IndexOf((char)x) > chars.IndexOf((char)y) ? 1 : 0;
    }
}

And I have a Array full of words. How exacly I can use this Compare to sort?

like image 418
Kio Coan Avatar asked Feb 14 '16 17:02

Kio Coan


People also ask

How do you sort an array in ascending order based on the ranks of each element which is in the another array?

The basic idea is to create a std::vector<std::pair<int,int>> and then simply sort that via std::sort . The rest of the code is about copying the values and ranks into that vector and copying the values out of it after sorting.

How do you sort an array in descending order using array sort?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.


1 Answers

I think that what you need is this. Declare a method for sorting as you already did.

public static int CompareStrings(string s1, string s2)
{
    // TODO: your code here
}

... and specify what function you need to use.

string[] myStrings = { ... };
Array.Sort(myStrings, CompareStrings);

If you use generic classes, you can achieve this as well doing as it follows:

List<string> myStrings = ...;
myStrings.Sort(CompareStrings);
like image 90
Simply Me Avatar answered Sep 21 '22 12:09

Simply Me