Structure sorting method in C# (Array.sort() + ICompare)

I feel that C# is more troublesome than C++, and there is less information. After searching for a long time, I didn't find a structure sort that can be used.

 

This is the structure to be sorted:

   public struct la
        {
           public int id;
           public int sb;
        };

 

 

First of all, C# needs to call a space (similar to the header file)

using System.Collections;

 

Secondly, the compare function of c# needs a class (the class is the compare function of traditional C++)

       public class cmp : IComparer //注意一定要是“public”,一定要是“class”,一定要是“IComparer”,“cmp”为自己随便起的名。
        {
            public int Compare(object x, object y) //这里很坑,一定注意必须为int,“Compare”看似是命名一个函数,但只能用这一个名字,object也不能改!!
            {
                la a = (la)(x);
                la b = (la)(y);//然后直接强转(很蠢)
                if (a.id < b.id) return -1;//小于0为x小于y
                else if (a.id > b.id) return 1;//大于0为x大于y
                else return 0;//等于0为x等于y
            }
        }

Finally, the sorting function should also be noted, the compare function needs to be declared!

    IComparer Cmp = new cmp();//不要忘记这一句
            Array.Sort(a,0,2,Cmp);

 

 

For those who are familiar with C++ and learn C#, some codes of C# are more cumbersome. (For example, the disgusting byte+byte=int, new must be used to declare the variable, obviously it doesn't need to be so troublesome )

Such as structure sorting, the sort encapsulated by <algorithm> is very convenient for the compare function, while the IComparer called by C# is more complicated

And C# syntax is too rigid, but it seems to have more functions.

 

Attach the complete code that can run:

using System;
using System.Collections;
namespace ConsoleApp1
{
    class Program
    {
       public struct la
        {
           public int id;
           public int sb;
        };
        public class cmp : IComparer //注意一定要是“public”,一定要是“class”,一定要是“IComparer”,“cmp”为自己随便起的名。
        {
            public int Compare(object x, object y) //这里很坑,一定注意必须为int,“Compare”看似是命名一个函数,但只能用这一个名字,object也不能改!!
            {
                la a = (la)(x);
                la b = (la)(y);//然后直接强转(很蠢)
                if (a.id < b.id) return -1;//小于0为x小于y
                else if (a.id > b.id) return 1;//大于0为x大于y
                else return 0;//等于0为x等于y
            }
        }
        static void Main(string[] args)
        {
            la[] a = new la[9];
            a[0].id = 2;a[0].sb = 1;
            a[1].id = 1;a[1].sb = 2;
            IComparer Cmp = new cmp();//不要忘记这一句
            Array.Sort(a,0,2,Cmp);
            for (int i = 0; i <= 1; i++)
                Console.WriteLine(a[i].sb);
        }
    }
}

If you have any questions about structure sorting, please comment. . (Although I am also very good)

 

Guess you like

Origin blog.csdn.net/haobang866/article/details/100129243