简体   繁体   中英

Sort a C# Array based on an object member?

I have a constructor with 2 (double) arrays members :

constructor[i].x and constructor[i].y ( where i is the number of elements )

How can I sort the x member : constructor[].x ?

With LINQ it is just

constructor = constructor.OrderBy(a => a.x).ToArray();

Without LINQ

class CustomClass
{
    public double x;
    public double y;
}

public class CustomComparer : IComparer<CustomClass>
{
    private CustomComparer() { }

    public static CustomComparer Instance { get { return _SingeltonInstance; } }

    private static CustomComparer _SingeltonInstance = new CustomComparer();

    public int Compare(CustomClass a, CustomClass b)
    {
        return a.x.CompareTo(b.x);
    }
}

public class myCode
{
    public void SomeFuction(CustomClass[] myClass)
    {
         //myClass is unsorted here;
         Array.Sort(myClass, CustomComparer.Instance);
         //myClass is sorted here;
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM