对数组进行降序排序

时间:2014-01-12 05:29:41

标签: c# arrays sorting

所以我现在有一个数组,可以从玩家选择的5个英雄中获取并存储一定值。这个价值是英雄倡议,我将用它来看看英雄先行等等。因此,例如,英雄一个被保存到保存到数组[0]的h1initiative变量,英雄二被保存到保存到数组[1]的h2initiative变量,依此类推。但是我在脚本的底部有一个排序功能,我相信虽然我不确定但它仍在工作。但我不完全确定如何使用排序功能允许我从最高到最低的顺序对代码中的变量进行排序,然后按顺序激活代码。所以例如Archer被保存到h1initiative / array [0],值为3,而berserker被保存到h2initiative / array [1],值为5.我想首先激活狂战士代码,然后激活之后的弓箭手狂战士已经完成,因为射手具有次高价值。我知道允许我激活脚本的代码,我只需要知道如何编写最高代码来执行此操作,然后下一个代码,依此类推。继承我的代码:

using UnityEngine;
using System.Collections;

public class InitiativeSorter : MonoBehaviour {
GameObject hOne;
GameObject hTwo;
GameObject hThree;
GameObject hFour;
GameObject hFive;
GameObject MainCamera;
public int h1Initiative = 0;
public int h2Initiative = 0;
public int h3Initiative = 0;
public int h4Initiative = 0;
public int h5Initiative = 0;
public int[] initiativeArray = new int[5];

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    initiativeArray[0] = h1Initiative;
    initiativeArray[1] = h2Initiative;
    initiativeArray[2] = h3Initiative;
    initiativeArray[3] = h4Initiative;
    initiativeArray[4] = h5Initiative;
    MainCamera = GameObject.Find("Main Camera");
    HeroArraySaver heroArraySaver = MainCamera.GetComponent<HeroArraySaver>();
    hOne = heroArraySaver.heroOne;
    hTwo = heroArraySaver.heroTwo;
    hThree = heroArraySaver.heroThree;
    hFour = heroArraySaver.heroFour;
    hFive = heroArraySaver.heroFive;

    Initiative initiative = hOne.GetComponent<Initiative>();
    h1Initiative = initiative.heroInitiative;

    Initiative initiative1 = hTwo.GetComponent<Initiative>();
    h2Initiative = initiative1.heroInitiative;

    Initiative initiative2 = hThree.GetComponent<Initiative>();
    h3Initiative = initiative2.heroInitiative;

    Initiative initiative3 = hFour.GetComponent<Initiative>();
    h4Initiative = initiative3.heroInitiative;

    Initiative initiative4 = hFive.GetComponent<Initiative>();
    h5Initiative = initiative4.heroInitiative;
    System.Array.Sort<int>(initiativeArray);



}

}

2 个答案:

答案 0 :(得分:3)

var sortedArray = initiativeArray.OrderByDescending(item => item);

答案 1 :(得分:1)

如果您想要访问OrderByDescending方法,则必须通过以下方式将linq添加到您的程序中:

using System.Linq;

然后可以访问OrderByDescending

var sortedArray = initiativeArray.OrderByDescending(item => item);

您可以通过以下方式访问最高价值:

var highestValue = sortedArray.First() 

此外,如果您想访问第n个元素,可以使用以下代码:

var 1st = sortedArray.ElementAt(0);    
var 2nd = sortedArray.ElementAt(1);
var 3rd = sortedArray.ElementAt(2);
...