Florin M.
Florin M.

Reputation: 2169

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 ?

Upvotes: 0

Views: 183

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127583

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;
    }
}

Upvotes: 1

Related Questions