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 ?

3
  • 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. Commented Apr 22, 2012 at 18:07
  • See stackoverflow.com/questions/1301822/… It's not an in-place Array sort, but it'll work in most cases. Or see the Array.Sort documentation. Commented Apr 22, 2012 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.) Commented Apr 22, 2012 at 18:16

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's not LINQ. LINQ (IEnumerable) uses OrderBy. There is, however, static Array.Sort and List.Sort.
@pst this was typed from memory from my phone. Corrected.
Just keeping you on your toes ;-)
Added a version that did not use any .NET 4 (LINQ) stuff

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.