sort array in that manner that sorted array's member starts in ascending order but o value comes at last in c#
ulong[] arr = new ulong[30];
arr[0]=13325647855656;
arr[1]=65897426666332;
arr[2]=00685956265661;
arr[4]=0;
then output must be
arr[0]=00685956265661;
arr[1]=13325647855656;
arr[2]=65897426666332;
arr[4]=0;
you can use Linq
OrderBy
and ThenBy
ulong[] arr = new ulong[30];
arr[0] = 13325647855656;
arr[1] = 65897426666332;
arr[2] = 00685956265661;
arr[4] = 0;
var results = arr.OrderBy(x => x == 0).ThenBy(x => x);
You can use Array.Sort
with this custom comparison delegate :
Array.Sort(arr, (u1, u2) =>
{
if (u1 == 0 && u2 == 0) return 0;
else if (u1 == 0) return ulong.MaxValue.CompareTo(u2);
else if (u2 == 0) return u1.CompareTo(ulong.MaxValue);
else return u1.CompareTo(u2);
});
If you want to use Linq ( ToArray()
needs to create an additonal array internally), i would use:
arr = arr.OrderBy(x => x == 0).ThenBy(x => x).ToArray();
class ZeroIsBigComparer : System.Collections.Generic.IComparer<ulong>
{
public int Compare(ulong x, ulong y)
{
if (x == y) return 0;
if (x == 0) return 1;
if (y == 0) return -1;
return x.CompareTo(y);
}
}
then
var comparer = new ZeroIsBigComparer();
arr = arr.OrderBy(x => x, comparer).ToArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.