c# - Unity C# 和数组排序

标签 c# arrays sorting unity3d

所以我知道如何在 php 中对数组进行排序并保留键,但我在统一方面遇到了一些麻烦。

假设我有一个数组 itemcost = new int[10];

    itemcost[1] = 100;
    itemcost[2] = 300;
    itemcost[3] = 900;
    itemcost[4] = 300;
    itemcost[5] = 100;
    itemcost[6] = 300;

什么是最好的方法来排序这个成本最高但保留数组键以便我可以获得相应的 def 和 att 值?

提前致谢。

最佳答案

Sort Generic List or Array of a class/structure based on class property or element property

创建一个类来保存成本及其索引,然后对此类的数组或列表进行排序

您可以为类中的每个项目添加 def、att、cost、name 属性

举个例子

public class CostData
    {
        public int Cost;
        public int ID;
        public CostData(int CostAmount, int CostID)
        {
            Cost = CostAmount;
            ID = CostID;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        List<CostData> itemcost = new List<CostData> {
                                                    new CostData(100, 1),
                                                    new CostData(300, 2),
                                                    new CostData(900, 3),
                                                    new CostData(300, 4),
                                                    new CostData(100, 5),
                                                    new CostData(300, 6)
                                                   };

        List<CostData> SortedList = itemcost.OrderByDescending((CostData i) => i.Cost).ToList();

        Console.WriteLine(SortedList[0].Cost.ToString() + " on index " + SortedList[0].ID.ToString());

        // you can do same with Arrray

        CostData[] itemcost2 = new CostData[] {
                                                    new CostData(100, 1),
                                                    new CostData(300, 2),
                                                    new CostData(900, 3),
                                                    new CostData(300, 4),
                                                    new CostData(100, 5),
                                                    new CostData(300, 6)
                                                   };

        CostData[] SortedList2 = itemcost2.OrderByDescending((CostData i) => i.Cost).ToArray();

        Console.WriteLine(SortedList2[0].Cost.ToString() + " on index " + SortedList2[0].ID.ToString());
    }

关于c# - Unity C# 和数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486461/

相关文章:

JavaScript 数组排序

C基数排序字符串数组

linux - 使用行字段排序命令输出

c# - 我应该为 Asp.NET web-api 路由使用 RouteParameter 还是 UrlParameter?

c - 用位域初始化结构常量数组

python - 导入自己的数据,例如 MNIST 或 CIFAR10 load_data()

php - 在 Laravel 中混淆数组和对象

c# - HttpClient 不适用于国际域名

c# - 温和地杀死一个进程

c# - Visual Studio 2012 Ordered Test,如何监控测试执行