0

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 ?

Florin M.
  • 2,159
  • 4
  • 39
  • 97
  • 3
    Please paste real code (including any *attempts* along with the *reason* for why they didn't work). There is no "Constructor" here, except for the name. –  Apr 22 '12 at 18:07
  • See http://stackoverflow.com/questions/1301822/how-to-sort-an-array-of-object-by-a-specific-field-in-c It's not an in-place Array sort, but it'll work in most cases. Or see the [Array.Sort](http://msdn.microsoft.com/en-us/library/system.array.sort.aspx) documentation. –  Apr 22 '12 at 18:09
  • (It would be interesting to see answers that shows use of Array.Sort, perhaps in addition to LINQ approaches. All the answers I could find on SO in my brief search were related to LINQ/IEnumerable and *not* specifically an Array. The benefit, and crutch, of Array.Sort is that it is mutating.) –  Apr 22 '12 at 18:16

1 Answers1

1

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;
    }
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431