c# 类的排序

IComparable

 一种特定于类型的通用比较方法,值类型或类通过实现此方法对特认定进行排序

IComparable的作用是提供了一种比较两个对象的特定类型的方法。这是必需的如果您想要为对象提供任何排序功能。视为IComparable提供您的对象的默认排序次序。例如对于如果您有一个您的类型的对象的数组,并在该数组上调用Sort方法IComparable在排序过程中提供对象的比较。实现IComparable接口时, 必须实现CompareTo方法

此接口由具有可排序值的类型实现。它要求实现类型定义单个方法CompareTo,该方法指示当前实例在排序顺序中的位置是位于同一类型的另一个对象之前、之后还是与其位置相同。

compareTo

 public int compareTo(Integer  anotherInteger)在数字上比较两个Integer对象。

如果该 Integer 等于 Integer 参数,则返回 0 值;如果该 Integer 在数字上小于 Integer 参数,则返回值-1;如果 Integer 在数字上大于 Integer 参数,则返回整数1

using System;

public class CropRenderInfo:IComparable<CropRenderInfo>
{
    public int cropID = 0;
    public int dailyRemainPlantTimes = 10;
    
    public int CompareTo(CropRenderInfo other)
    {
        if(this.dailyRemainPlantTimes <= 0)
        {
            if(other.dailyRemainPlantTimes <= 0)
            {
                if(this.cropID > other.cropID)
                {
                    return 1;
                }
                else if(this.cropID == other.cropID)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
            else
            {
                return 1;
            }
        }
        else
        {
            if (other.dailyRemainPlantTimes <= 0)
            {
                return -1;
            }
            else
            {
                if (this.cropID > other.cropID)
                {
                    return 1;
                }
                else if (this.cropID == other.cropID)
                {
                    return 0;
                }
                else
                {
                    return -1;
                }
            }
        }
    }
}

排序时用sort直接排序

private void InitCropRenderInfoList()
    {
        cropRenderInfoList = new List<CropRenderInfo>();
        for (int i = 0; i < 15; i++)
        {
            CropRenderInfo cropRenderInfo = new CropRenderInfo();
            cropRenderInfo.cropID = i + 1;
            CropInfo cropInfo = DataManager.Instance.GetCropInfo(cropRenderInfo.cropID);
            cropRenderInfo.dailyRemainPlantTimes = PlayerInfo.Instance.GetPropCount(cropInfo.taskItemID);
            cropRenderInfoList.Add(cropRenderInfo);
        }
        cropRenderInfoList.Sort();
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值