我正在用 c# 制作一個腳本,它需要一個函式來使用多個引數創建排行榜。這是排行榜之一的示例:
粗體列是排行榜的第一項檢查,然后移動到左側的列,依此類推。
我的想法是為每列創建一個 for 回圈并對四個值進行排序。
int[] tempScores = new int[scores[0].Length];
for (int i = 0; i < scores[0].Length; i )
{
if (scores[0][i] < scores[0][i 1]) tempScores[i] = scores[0][i 1];
else if (scores[0][i] > scores[0][i 1]) tempScores[i] = scores[0][i];
else if (scores[0][i] == scores[0][i 1])
{
// Do same thing but for next column : scores[1]
}
}
這段代碼可以在 90% 的時間內作業,但有時兩個或更多的值會被反轉。它只是不適用于這樣的排行榜:

因此,如果有人對我的問題有答案或更有效的方法,我很想知道如何解決。
uj5u.com熱心網友回復:
我讀了這篇文章,第一個想到的是 Linq。您需要做的就是按您關心的第一個屬性排序,然后按所有其他屬性排序。
首先是創建一個可以保存您的國家/地區資料的類。
它可能看起來像這樣:
public class CountryData
{
public string Name { get; set; }
public int Prop1 { get; set; }
public int Prop2 { get; set; }
public int Prop3 { get; set; }
public int Prop4 { get; set; }
public int Prop5 { get; set; }
public int Prop6 { get; set; }
public int Prop7 { get; set; }
public int Prop8 { get; set; }
}
我不知道這些屬性是什么意思,因為你沒有說,所以我暫時給了它們一個通用名稱。你總是可以把它改成更有意義的東西
好的,現在我們有了這個,我們需要實際的排序。
我們可以撰寫另一個類來做到這一點:
public class OrderLogic
{
public List<CountryData> SortCountries(List<CountryData> countriesData)
{
return countriesData
.OrderByDescending(p => p.Prop8)
.ThenByDescending(p => p.Prop7) //continue with as many orders as you need
.ToList();
}
}
最后,我們如何使用它?
我會為此撰寫一個測驗,以確保邏輯運行良好:
[Test]
public void Test1()
{
List<CountryData> countriesData = new List<CountryData>();
countriesData.Add(new CountryData { Name = "Switzerland", Prop1 = 3, Prop2 = 1, Prop3 = 1, Prop4 = 1, Prop5 = 4, Prop6 = 5, Prop7 = -1, Prop8 = 4 });
countriesData.Add(new CountryData { Name = "Italy", Prop1 = 3, Prop2 = 3, Prop3 = 0, Prop4 = 0, Prop5 = 7, Prop6 = 0, Prop7 = 7, Prop8 = 9 });
countriesData.Add(new CountryData { Name = "Wales", Prop1 = 3, Prop2 = 1, Prop3 = 1, Prop4 = 1, Prop5 = 3, Prop6 = 2, Prop7 = 1, Prop8 = 4 });
countriesData.Add(new CountryData { Name = "Turkey", Prop1 = 3, Prop2 = 0, Prop3 = 0, Prop4 = 3, Prop5 = 1, Prop6 = 8, Prop7 = -7, Prop8 = 0 });
var result = new OrderLogic().SortCountries(countriesData);
Assert.IsTrue(result[0].Name.Equals("Italy"));
Assert.IsTrue(result[1].Name.Equals("Wales"));
Assert.IsTrue(result[2].Name.Equals("Switzerland"));
Assert.IsTrue(result[3].Name.Equals("Turkey"));
}
好了,測驗通過了,您可以盡情重構,因為您知道不會破壞實際邏輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342949.html
上一篇:用變數引數化函式。然后洗掉變數
