Farseer

导航

D365 FO Array增加排序

X++的集合类,Array,List,Set里没有可以提供排序的功能,如果要对元素排序不是很方便。

D365 FO支持扩展,所以可以很方便地给这些集合类增加排序功能,这里以Array为例,只实现了数值和字符串的排序,至于class和record类型的,目前还没遇到需要排序的场景,就暂时不实现了,用到再说。

[ExtensionOf(classStr(Array))]
public final class Array_Class_Extension
{       
    /// <summary>
    /// 使用快速排序法对Array元素进行排序    
    /// </summary>
    public void sort()
    {
        this.quickSort(1, this.lastIndex());        
    }    
    private void quickSort(
      int _left, 
      int _right)
    {
        int i = _left;
        int j = _right;        
        if (i < j)
        {
            anytype pivot = this.value(i);
            while (i < j)
            {
                while (this.greaterThan(this.value(j), pivot) && (i < j))
                {
                    j--;
                }                
                this.value(i, this.value(j));                
                while (this.lessThanOrEqual(this.value(i), pivot) && (i < j))
                {
                    i++;
                }
                this.value(j, this.value(i));
            }
            this.value(i, pivot);
            this.QuickSort(_left, i - 1);
            this.QuickSort(j + 1, _right);
        }
    }

    private boolean greaterThan(
        anytype _valueLeft, 
        anytype _valueRight)
    {        
        switch (this.typeId())
        {
            case Types::Int64:
            case Types::Integer:
            case Types::Real:
                return _valueLeft > _valueRight;
            default:
                return strCmp(_valueLeft.toString(), _valueRight.toString()) == 1;
        }
    }

    private boolean lessThanOrEqual(
        anytype _valueLeft,
        anytype _valueRight)
    {
        switch (this.typeId())
        {
            case Types::Int64:
            case Types::Integer:
            case Types::Real:                
                return _valueLeft <= _valueRight;
            default:
                return strCmp(_valueLeft.toString(), _valueRight.toString()) == -1 
                        || strCmp(_valueLeft.toString(), _valueRight.toString()) == 0;
        }
    }

    /// <summary>
    /// 把排序后的数组以字符串方式拼接输出
    /// </summary>
    /// <param name = "_delimiter">元素之间的分隔符</param>
    /// <returns>排序后以分隔符连接的字符串</returns>
    public str sortString(str _delimiter = "")
    {
       this.sort();

        str destStr = "";
        for (int i = 1; i <= this.lastIndex(); i++)
        {
            destStr += this.value(i).ToString() + _delimiter;
        }
        if (_delimiter)
        {
            return subStr(destStr, 1, strLen(destStr) -1);
        }
        else
        {
            return destStr;
        }
    }

}

posted on 2020-12-26 11:17  佛西亚  阅读(179)  评论(0编辑  收藏  举报