private class MyComparer : IComparer<string>
{
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return -StrCmpLogicalW(psz1, psz2);
}
}
When I'm adding minus in the return line it will sort the array from the last item to the first. Without the minus it will sort the array and will keep the order from the first to the last.
The minus just make the sorting also to reverse the array.
I want somehow to make a bool so I can select if to reverse or not the array.
Usage :
Array.Sort(files, new MyComparer());
I want to be able to decide if to reverse it or not by setting true or false for example :
Array.Sort(filesRadar, new MyComparer(false));
If false don't reverse it return without minus if true add minus.
CodePudding user response:
You can pass reverse
into the constructor:
private class MyComparer : IComparer<string>
{
// We may want to get rid of creation (see @aybe comment below)
public static readonly MyComparer Ascending = new MyComparer();
public static readonly MyComparer Descending = new MyComparer(false);
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return (Reverse ? -1 : 1) * StrCmpLogicalW(psz1, psz2);
}
public MyComparer(bool reverse) {
Reverse = reverse;
}
public MyComparer()
: MyComparer(false) {}
public bool Reverse {get; private set;}
}
Then you can put
Array.Sort(filesRadar, new MyComparer(false));
Or even
Array.Sort(filesRadar, MyComparer.Ascending);
CodePudding user response:
Try something like this:
bool SortArrayReversed = false;
if(SortArrayReversed == false)
{
Array.Sort(files);
}
else
{
Array.Sort(-files);
}
When you want to switch the way the array is sorted, just change the SortArrayReversed value.