首页 > 解决方案 > 如何检查我是否在 if 语句中越界?

问题描述

我有一个循环试图对数据进行排序和组织。

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,但这似乎不起作用。是否有我可以使用的异常或检查它是否超出范围的东西?

标签: c#

解决方案


而不是这个

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();

(但你真的应该将这两个信息存储在同一个类中,或者至少不要通过索引链接)


推荐阅读