關于List<T>.FindLast的應用小例子
實際游戲開發中,經常會有這種需求,比如玩家當前精通值1500,需要判斷玩家當前的精通評價,如表。

按1500精通值,那么區間在1000~2000之間,玩家當前的正確評價是【略知一二】
首先最容易想到的循環遍歷比對方式,沒問題,但似乎有點僵硬,想著是不是可以改進一下
public SwordProficientConfig GetProficientLevel(int proficientValue)
{
//如果精通值>=最后1條記錄,直接返回最后一個記錄
if (proficientValue>=this.DataList[^1].SumProficientValue)
{
return this.DataList[^1];
}
for (int i = 0; i < this.DataList.Count; i++)
{
//如果不是最后1條,比對是否 >=當前記錄 且 <下條記錄
if (proficientValue>=this.DataList[i].SumProficientValue && proficientValue<this.DataList[i+1].SumProficientValue)
{
return this.DataList[i];
}
}
return this.DataList[0];
}
群里詢問,大佬建議可以試試Find方法,于是自己去查了Find的用法,重新嘗試。寫完之后,emm.....用了,但是沒完全用,判斷思路上還是沒有脫離第一種寫法,而且顯得更累贅,思維要跳出來。
public SwordProficientConfig GetProficientLevel2(int proficientValue)
{
//如果精通值>=最后1條記錄,直接返回最后一個記錄
if (proficientValue>=this.DataList[^1].SumProficientValue)
{
return this.DataList[^1];
}
//如果不是最后1條,比對是否 >=當前記錄 且 <下條記錄
return this.DataList.Find(delegate(SwordProficientConfig config)
{
int nextIndex = this.DataList.IndexOf(config)+1;
return proficientValue >= config.SumProficientValue && proficientValue < this.DataList[nextIndex].SumProficientValue;
});
}
嘗試改進,簡潔了一些,但是有兩個問題:
1、如果精通值>最大值,還是需要單獨判斷一次,不夠簡潔;
2、結果不正確,返回的是2000的記錄,而不是1000的記錄,因為1500不會<2000,那么2000就是首條匹配記錄了;
public SwordProficientConfig GetProficientLevel3(int proficientValue)
{
//如果精通值>=最后1條記錄,直接返回最后一個記錄
if (proficientValue>=this.DataList[^1].SumProficientValue)
{
return this.DataList[^1];
}
//返回精通值>配置值的最后一條記錄
return this.DataList.Find(config => proficientValue < config.SumProficientValue);
}
最后把條件逆轉一下,然后采用FindLast來返回最后一條符合的記錄,完美,一行搞定!
public SwordProficientConfig GetProficientLevel3(int proficientValue)
{
//返回精通值>配置值的最后一條記錄
return this.DataList.FindLast(config => proficientValue > config.SumProficientValue);
}

浙公網安備 33010602011771號