关于list的排序问题

这篇博客介绍了如何创建一个名为BadGuy的类,包含name和power两个字段,并用它来初始化一个List。接着展示了如何使用Insert方法向列表中添加元素,并通过实现IComparable接口对BadGuy对象按power属性进行排序。最后,博客通过foreach循环打印排序后的列表内容并清空列表。
摘要由CSDN通过智能技术生成

首先定义一个List类
列表是泛型类,可以存储任意类型,本文中,我们先创建BadGuy类,有两个公共字段 namepower

public class BadGuy :
{
    public string name;
    public int power;
    public BadGuy(string newname, int newpower)    //公共构造函数
    {
        name = newname;
        power = newpower;
    }
}

之后创建列表并分配内容。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SomeClasses : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {
        List<BadGuy> badGuys = new List<BadGuy>();
        badGuys.Add(new BadGuy("Harvey", 50));
        badGuys.Add(new BadGuy("Pip", 5));
        badGuys.Add(new BadGuy("Magneto", 100));
        badGuys.Add(new BadGuy("Nageto", 100));
        badGuys.Insert(1,new BadGuy("Hippop",150));

        badGuys.Sort();   //排序,需要Icomparable接口
        
        foreach (BadGuy guy in badGuys)  
        {
            print(guy.name + " " + guy.power);
        }
        badGuys.Clear();


    }

依赖接口

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;   //IComparable的引用

public class BadGuy : IComparable<BadGuy>
{
    public string name;
    public int power;
    public BadGuy(string newname, int newpower)
    {
        name = newname;
        power = newpower;
    }
    // 以下为生序排列,CompareTo 方法返回正值时,比较对象大于other,0相等,负数反之
    public int CompareTo(BadGuy other)
    {
        if (other ==null)
        {
            return 1;
        }
        return power - other.power ;   
        //降序排列  
        // return  other.power -  power;   

    }

  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值