C# 数组/集合排序

一:基础类型集合排序

/// <summary>
/// 排序
/// </summary>
/// <param name="isReverse">顺序是否取反</param>
public static void Sort<T>(this IList<T> array, bool isReverse = false)
	where T : IComparable
{
    var count = array.Count;
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < count; j++)
        {
            var k = j + 1;
            if (k >= count)
                break;

            if (!isReverse)
            {
                if (array[j].CompareTo(array[k]) == 1)
                    (array[j], array[k]) = (array[k], array[j]);
            }
            else
            {
                if (array[j].CompareTo(array[k]) == -1)
                    (array[j], array[k]) = (array[k], array[j]);
            }
        }
    }
}

测试:

if (Input.GetKeyDown(KeyCode.Space))
{
    // 字符串数组
    var strArray = new[] {"8", "1", "J", "D","A", "B1"};
    strArray.Sort(true);
    string str0 = "";
    for (int i = 0; i < strArray.Length; i++)
    {
        str0 += strArray[i] + ((i + 1 < strArray.Length) ? "、" : "");
    }
    Debug.LogError(str0);
                
                
    // int数组
    var intArray = new[] {8, 1, 10, 5, 9, 7};
    intArray.Sort();
    string str1 = "";
    for (int i = 0; i < intArray.Length; i++)
    {
        str1 += intArray[i] + ((i + 1 < intArray.Length) ? "、" : "");
    }
    Debug.LogError(str1);
}

在这里插入图片描述

二:排序扩展(根据某个类型排序)

[System.Runtime.InteropServices.ComVisible(true)]
public interface IComparableByEnum : IComparable
{
    int CompareTo(Enum sortEnum, object compareObj);
}

/// <summary>
/// 排序
/// </summary>
/// <param name="sortEnum">依据什么类型排序</param>
/// <param name="isReverse">顺序是否取反</param>
public static void Sort<T>(this IList<T> array, Enum sortEnum, bool isReverse = false)
    where T : IComparableByEnum
{
    var count = array.Count;
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < count; j++)
        {
            var k = j + 1;
            if (k >= count)
                break;

            if (!isReverse)
            {
                if (array[j].CompareTo(sortEnum, array[k]) == 1)
                    (array[j], array[k]) = (array[k], array[j]);
            }
            else
            {
                if (array[j].CompareTo(sortEnum, array[k]) == -1)
                    (array[j], array[k]) = (array[k], array[j]);
            }
        }
    }
}
public enum SortType
{
    Id,
    Name,
}
        
public class MyClass : IComparableByEnum
{
    public int id;
    public string name;

    public MyClass(int _id, string _name)
    {
        id = _id;
        name = _name;
    }

    public int CompareTo(object obj)
    {
        return CompareTo(MySortType.Id, obj);
    }

    public int CompareTo(Enum sortEnum, object compareObj)
    {
        if (!(sortEnum is SortType sortType))
            return -1;

        if (!(compareObj is MyClass value))
            throw new ArgumentException($"参数不是{nameof(MyClass)}类型");

        return sortType switch
        {
            SortType.Id => id.CompareTo(value.id),
            SortType.Name => string.Compare(name, value.name, StringComparison.CurrentCulture),
            _ => throw new ArgumentException($"排序类型出错{sortType}")
        };
    }
}

测试:

private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        var list = new List<MyClass>()
        {
            new MyClass(5,"Zz"),
            new MyClass(86,"C"),
            new MyClass(1,"Aa"),
            new MyClass(0,"Bb"),
            new MyClass(20,"Tt"),
        };
                
        list.Sort(SortType.Id);
        string str0 = "";
        for (int i = 0; i < list.Count; i++)
        {
            str0 += $"{list[i].id};{list[i].name}" + (i + 1 < list.Count? "、" : "");
        }
        Debug.LogError(str0);

        list.Sort(SortType.Name);
        string str1 = "";
        for (int i = 0; i < list.Count; i++)
        {
            str1 += $"{list[i].name};{list[i].id}" + (i + 1 < list.Count? "、" : "");
        }
        Debug.LogError(str1);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值