基于对象成员对C#数组进行排序?

时间:2012-04-22 17:56:46

标签: c# sorting

我有一个带有2个(双)数组成员的构造函数:

constructor [i] .x和constructor [i] .y(其中i是元素的数量)

如何对x成员进行排序:constructor []。x?

1 个答案:

答案 0 :(得分:1)

使用LINQ只是

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

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