簡體   English   中英

如何檢查if語句中是否超出界限?

[英]How Do I Check To See If I'm Out Of Bounds In An If Statement?

我有一個試圖排序和組織數據的循環。

for (int a = 0; a < Combos.Count; a++)
{
    //Largest to smallest

    if (Combos.Count - a >= 1)
    {
        if (scores[a + 1] != null)
        {
            Combos.Add(Combos[a]);
            Combos.RemoveAt(a);
            scores.Add(scores[a]);
            scores.RemoveAt(a);
        }
    }
}

我想在嵌套的if語句有效時執行它,在Java中我通常使用== null,但是這似乎不起作用。 我可以使用異常或其他方法檢查是否超出范圍嗎?

代替這個

if (scores[a + 1] != null)

您檢查Count (列表)或Length (數組):

if (a + 1 <= scores.Count)

不清楚您要在這里做什么,但是我想有很多更簡單的方法

 //Largest to smallest 

例如,使用LINQ:

var orderedCombos = Combos.Zip(scores, (c, s) => new{ Combo = c, Score = s})
    .OrderByDescending(x => x.Score)
    .Select(x => x.Combo)
    .ToList();

(但您實際上應該將這兩種信息都存儲在同一類中,或者至少不要通過索引鏈接)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM