2017-11-25 73 views
1

所以我知道如何在PHP中排序數組,並保持鍵,但我有一些麻煩統一。統一C#和數組排序

可以說我有一個數組 itemcost = new int [10];

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

什麼是排序最好的辦法降使成本最高的往上頂,但保持數組鍵,所以我可以得到相應的def ATT值?

在此先感謝。

+0

不要使用單獨的值的陣列,使用的是包含用於所有相關的值屬性的類的陣列(或列表)。 – CodeCaster

+0

當然,這將是理想的,但問題是,雖然這很容易讓我在PHP中做,在C#這是很難做! – Adam

+0

說我有每個項目def,att,cost,name屬性什麼是最好的存儲方式,通過att(降序)排序然後得到列表中的第二項? – Adam

回答

1
var result = Enumerable.Range(0, itemcost.Length) 
       .OrderByDescending(index => itemcost[index]) 
       .ToList(); 

result.ForEach(index => Console.WriteLine(index + " : " + itemcost[index])); 

將返回按順序排序的物料成本索引列表。

參見here

2

排序泛型列表或類/結構的陣列基於類屬性或元素屬性

創建一個類來保存成本及其索引然後進行排序的數組或列表這個類

你可以添加事件閃避,ATT,成本,每個項目名稱屬性類

我這裏是

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()); 
    } 
+0

他需要保持數組的索引。 –

+0

好的修改我的答案 –

1

Array.Sort(Array keys, Array items)

在keysArray每個鍵在itemsArray相應的項目。在排序過程中重新定位某個鍵時,itemsArray中的相應項目也會重新定位。因此,itemsArray根據keysArray中相應鍵的排列進行排序。

int[] indices = new int[itemcost.Length]; 

for (int i = 0; i < itemcost.Length; i++) 
{ 
    indices[i] = i; 
} 

Array.Sort(itemcost, indices);