今天我们来一起看一下关于集合List中的排序方法,大家都知道我们一般拿到一些数据的时候会放到一个容器中去,然后根据其中的一种属性来进行排序。我们很自然的就能想到sort()方法去自动排序。这样排序比较快,sort有三种结果 1,-1,0分别是大,小,相等。默认List的排序是升序排序,但是这个方法的后面有重载版本,今天我们一起来看一下吧!
首先我们来创建一个类吧!叫什么呢?就叫人类吧。

public class People
{
    public string name { get; set; }
    public int age { get; set; }

}

这个类有两个属性,一个是姓名,一个是年龄。接下来我们给它排序吧!

第一种:通过新建类的方式来排序

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

public class TestListSort : MonoBehaviour
{
    private List<People> peoples = new List<People>();

    // Use this for initialization
    void Start()
    {
        peoples.Add(new People() { name = "小明", age = 21 });
        peoples.Add(new People() { name = "小李", age = 24 });
        peoples.Add(new People() { name = "小玉", age = 22 });
        peoples.Add(new People() { name = "小红", age = 18 });
        peoples.Add(new People() { name = "小王", age = 17 });

        peoples.Sort(new PeopleCompare());

        foreach (var people in peoples)
        {
            print(people.name + people.age);
        }
    }

    static int AgeCompare(People x, People y)
    {
        if (x.age > y.age)
        {
            return 1;
        }
        else if (x.age == y.age)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }


    class PeopleCompare : IComparer<People>
    {
        public int Compare(People x, People y)
        {
            return AgeCompare(x, y);
        }
    }
}



第二种使用委托Comparis来排序

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

public class TestListSort : MonoBehaviour
{
    private List<People> peoples = new List<People>();

    // Use this for initialization
    void Start()
    {
        peoples.Add(new People() { name = "小明", age = 21 });
        peoples.Add(new People() { name = "小李", age = 24 });
        peoples.Add(new People() { name = "小玉", age = 22 });
        peoples.Add(new People() { name = "小红", age = 18 });
        peoples.Add(new People() { name = "小王", age = 17 });

        peoples.Sort(delegate (People p1, People p2)
        {
            return p1.age.CompareTo(p2.age);
        });

        foreach (var people in peoples)
        {
            print(people.name + people.age);
        }
    }

}


当然了,这样也可以用Lambda表达式来排序。显得更加的简洁。

 peoples.Sort((People p1, People p2) => p1.age.CompareTo(p2.age));

好了,这就是list中sort()方法的重载排序方法啦!今天就写到这里吧!

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐